guidance on writing XML

I'm creating some XML documents in my C# .net 2.0 code. To date I've mostly 
only read XML. Now I'm writing it and I'm struggling to figure out the best 
ways to do it and the best classes to use. Essentially I'm starting with a 
XML file that contains the root and start and end elements and I want to add 
instances of a child element to the file. Since XMLWriter is forward-only, 
it seemed to not be the best tool but maybe I'm misunderstanding it. I then 
moved on to XPathNavigator but am stumbling trying to add some CDATA. I've 
googled for some code samples but haven't turned anything definitive up. Any 
links to some good examples or just general guidance on this? Can I position 
the cursor with XMLWriter such that I can add child elements to an existing 
XML file or is it more for creating XML docs from scratch in one shot?

Thanks

Darren 

0
8/28/2007 11:00:40 PM
dotnet.xml 7266 articles. 0 followers. Follow

5 Replies
443 Views

Similar Articles

[PageSpeed] 32

Darren Mar-Elia wrote:
> I'm creating some XML documents in my C# .net 2.0 code. To date I've 
> mostly only read XML. Now I'm writing it and I'm struggling to figure 
> out the best ways to do it and the best classes to use. Essentially I'm 
> starting with a XML file that contains the root and start and end 
> elements and I want to add instances of a child element to the file. 
> Since XMLWriter is forward-only, it seemed to not be the best tool but 
> maybe I'm misunderstanding it. I then moved on to XPathNavigator but am 
> stumbling trying to add some CDATA. I've googled for some code samples 
> but haven't turned anything definitive up. Any links to some good 
> examples or just general guidance on this? Can I position the cursor 
> with XMLWriter such that I can add child elements to an existing XML 
> file or is it more for creating XML docs from scratch in one shot?

If you have an existing XML document and want to manipulate it then 
System.Xml.XmlDocument and the DOM implementation is the right tool, 
load the existing document with the Load method, then use methods like 
CreateElement and InsertBefore or AppendChild to create and insert new 
elements. As XmlDocument implements IXPathNavigable you can also use 
CreateNavigator and use the various edit method XPathNavigator allows. 
See <http://msdn2.microsoft.com/en-us/library/20esef39(VS.80).aspx>

-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1778)
8/29/2007 11:19:08 AM
Martin-
Thanks for that. I was playing with XMLDocument late last night :-). I guess 
my question is, what is the general approach for adding new nodes? For 
example, I have two nested elements in my existing document. I want to add 
my new elements as children of the inner element. So, do I first create a 
reference to the parent element where I want to start my adds and then 
simply start doing AppendChild? Also, once I've added a new element, do I 
have to position the cursor explicitly on that element to add, for example, 
a CDATA section to it? The reason I ask is that my biggest problem is not 
adding new nodes, but it putting them where I want them. It seems to be all 
over the map, based on my limited experience.

Thanks,

Darren


"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:uxsLt5i6HHA.1168@TK2MSFTNGP02.phx.gbl...
> Darren Mar-Elia wrote:
>> I'm creating some XML documents in my C# .net 2.0 code. To date I've 
>> mostly only read XML. Now I'm writing it and I'm struggling to figure out 
>> the best ways to do it and the best classes to use. Essentially I'm 
>> starting with a XML file that contains the root and start and end 
>> elements and I want to add instances of a child element to the file. 
>> Since XMLWriter is forward-only, it seemed to not be the best tool but 
>> maybe I'm misunderstanding it. I then moved on to XPathNavigator but am 
>> stumbling trying to add some CDATA. I've googled for some code samples 
>> but haven't turned anything definitive up. Any links to some good 
>> examples or just general guidance on this? Can I position the cursor with 
>> XMLWriter such that I can add child elements to an existing XML file or 
>> is it more for creating XML docs from scratch in one shot?
>
> If you have an existing XML document and want to manipulate it then 
> System.Xml.XmlDocument and the DOM implementation is the right tool, load 
> the existing document with the Load method, then use methods like 
> CreateElement and InsertBefore or AppendChild to create and insert new 
> elements. As XmlDocument implements IXPathNavigable you can also use 
> CreateNavigator and use the various edit method XPathNavigator allows. See 
> <http://msdn2.microsoft.com/en-us/library/20esef39(VS.80).aspx>
>
> -- 
>
> Martin Honnen --- MVP XML
> http://JavaScript.FAQTs.com/ 

0
8/29/2007 4:10:12 PM
Darren Mar-Elia wrote:

> Thanks for that. I was playing with XMLDocument late last night :-). I 
> guess my question is, what is the general approach for adding new nodes? 
> For example, I have two nested elements in my existing document. I want 
> to add my new elements as children of the inner element. So, do I first 
> create a reference to the parent element where I want to start my adds 
> and then simply start doing AppendChild? Also, once I've added a new 
> element, do I have to position the cursor explicitly on that element to 
> add, for example, a CDATA section to it? The reason I ask is that my 
> biggest problem is not adding new nodes, but it putting them where I 
> want them. It seems to be all over the map, based on my limited experience.

AppendChild/InsertBefore/InsertAfter need to be called on the new parent 
node so you are right to select that parent first (e.g. with 
SelectSingleNode) to be able to call AppendChild or InsertBefore or 
InsertAfter.

As for providing the contents of newly created elements (with .NET) you 
simply do that like this:

   XmlElement element = xmlDocumentInstance.CreateElement("element-name");
   element.InnerText = "element content";
   newParentElement.AppendChild(element);

If you want to add a CDATA section then you can't set InnerText but 
simply do e.g.

   XmlElement element = xmlDocumentInstance.CreateElement("element-name");
   element.AppendChild(xmlDocumentInstance.CreateCDATASection(
"foo & bar"));
   newParentElement.AppendChild(element);

So there is no cursor concept, you are dealing with nodes that have 
properties like InnerText and InnerXml and methods like AppendChild or 
InsertBefore. With newly created nodes there is no need to position 
anything as the methods like CreateElement return a reference to the 
node and you can then apply methods and set properties directly.


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1778)
8/30/2007 12:19:10 PM
Thanks Martin-
I did end up figuring this out. I have to admit it was less intuitive than 
other aspects of the framework but in the end, I got it to do what I wanted. 
Thanks again for your hints in the right direction!

-- 
Darren


"Martin Honnen" <mahotrash@yahoo.de> wrote in message 
news:%23Jrp6$v6HHA.1148@TK2MSFTNGP05.phx.gbl...
> Darren Mar-Elia wrote:
>
>> Thanks for that. I was playing with XMLDocument late last night :-). I 
>> guess my question is, what is the general approach for adding new nodes? 
>> For example, I have two nested elements in my existing document. I want 
>> to add my new elements as children of the inner element. So, do I first 
>> create a reference to the parent element where I want to start my adds 
>> and then simply start doing AppendChild? Also, once I've added a new 
>> element, do I have to position the cursor explicitly on that element to 
>> add, for example, a CDATA section to it? The reason I ask is that my 
>> biggest problem is not adding new nodes, but it putting them where I want 
>> them. It seems to be all over the map, based on my limited experience.
>
> AppendChild/InsertBefore/InsertAfter need to be called on the new parent 
> node so you are right to select that parent first (e.g. with 
> SelectSingleNode) to be able to call AppendChild or InsertBefore or 
> InsertAfter.
>
> As for providing the contents of newly created elements (with .NET) you 
> simply do that like this:
>
>   XmlElement element = xmlDocumentInstance.CreateElement("element-name");
>   element.InnerText = "element content";
>   newParentElement.AppendChild(element);
>
> If you want to add a CDATA section then you can't set InnerText but simply 
> do e.g.
>
>   XmlElement element = xmlDocumentInstance.CreateElement("element-name");
>   element.AppendChild(xmlDocumentInstance.CreateCDATASection(
> "foo & bar"));
>   newParentElement.AppendChild(element);
>
> So there is no cursor concept, you are dealing with nodes that have 
> properties like InnerText and InnerXml and methods like AppendChild or 
> InsertBefore. With newly created nodes there is no need to position 
> anything as the methods like CreateElement return a reference to the node 
> and you can then apply methods and set properties directly.
>
>
> -- 
>
> Martin Honnen --- MVP XML
> http://JavaScript.FAQTs.com/ 

0
8/31/2007 1:40:56 AM
Darren Mar-Elia wrote:

> I did end up figuring this out. I have to admit it was less intuitive 
> than other aspects of the framework but in the end, I got it to do what 
> I wanted. 

With .NET 3.5 (respectively Visual Studio 2008) you will have LINQ and 
LINQ to XML which is supposed to be more intuitive than DOM. But 
currently it is only in beta.
The beta documentation is online here: 
<URL:http://msdn2.microsoft.com/en-us/library/bb387098(VS.90).aspx>

Creating an element with text content is then as "easy" as e.g.

   XElement newElement = new XElement("element-name", "element content");

Creating an element with child elements then works as follows:

   XElement newElement = new XElement("element-name",
     new XElement("child-name", "foo"),
     new XElement("child-name", "bar")
   );


-- 

	Martin Honnen --- MVP XML
	http://JavaScript.FAQTs.com/
0
mahotrash (1778)
8/31/2007 12:25:57 PM
Reply:

Similar Artilces:

xml graphic representation
I'm new to using XML, so I'm seeking some general pointers about approaching a project. I'd like to read the sitemap xml file, and generate a graphic representation of the website from the site map. I would like to do this dynamically (creating the page from the current sitemap file). I'm wondering if there are some built in functions I can use, for example to: 1) parse the xml file, creating units at each node 2) interpret levels within the file 3) create graphics based on each node, writing the node property in the text of the graphic object. I know what functions I'...

writing area
I know that I can select an area: ex: A1 to b9. After selecting it is then possible to write and the marker will automatically move from a1 to b1 to c1 as you press enter (instead of moving down one and one row). However - I do not remember how I can mark the area for writing. Please help anyone!? Under Tools/Options/Edit, you can set the direction that the cell pointer moves. On Wed, 20 Oct 2004 20:05:01 +0200, "Kathrine J Wathne" <kjwathne@start.no> wrote: >I know that I can select an area: ex: A1 to b9. After selecting it is then >possible to write and the ma...

generate xml ...
hi, i need to generate an xml files of some data in my database ... i've an xml sample of the result xml nad i've to create a xml with the same structure ... which it is the better and faster way? Can i retrieve a schema from the sample.xml and then write an xml based on this schema ? Might i use Dataset.readxmlschema , Dataset.readxml and Dataset.writexmlschema , Dataset.writexml ??? tnx in advance andrew ...

excel to xml
Hello I am trying to figure this out. Yes there is some new feature in excel 2003 according to the websites that I browsed thro' It is about transforming a excel spreedsheet into Xml with the syntax you wanted instead of repeating cut and paste of the syntax in an Xml file. I was reading in msdn that excel 2003 has these features but I have no clue. When I give file save as in an excel file .I have many features I can save as to,so when I select save as xml data .I can include an xml map to map to the excel fields but after that it doesn't go forward for me. I nee...

novice trying to write formula
I'm trying to write a formula: If column D = K or any number 1 - 12 and K = A then L = NL ( or I could use the number 1) Please remember I'm a novice EXCEL user...and what little I know i self-taught. thanks -- Message posted from http://www.ExcelForum.com Mary It's somewhat difficult to follow what you're saying. Does "column D = K" mean "column D = column K" or is it "column D = the letter K"? And what does "K = A" mean? And what does "then L = NL ( or I could use the number 1)" mean? HTH Otto "mary...

Line Breaks in XML element value
I am using the XPathNavigator.Value in .Net to get the value of one of the elements(say "Notes") from my XML ? The value contains lots of "line breaks" and "spaces". <notes> This is to try the new car that I bought last week </notes> How do I avoid getting the "linebreaks" and extra "white spaces" ? I just want the string "This is to try the new car that I bought last week". Venky wrote: > I am using the XPathNavigator.Value in .Net to get the > value of one of the elements(say "Notes&quo...

Write to Registry
How to write to registry from MFC 6.0? I want to change my settings for header and footer for IE 6 Regards, Mystique > I want to change my settings for header and footer for IE 6 How doing the above is related to writing to registry using MFC? You can use Reg* fucntions (eg RegOpenKey, RegCloseKey, RegQueryValue, RegSetValue etc) in Win32. MFC provides similar functionality for its framework. Take a look at GetProfileString, tProfileInt, WriteProfileInt etc. -- Ajay Kalra [MVP - VC++] ajaykalra@yahoo.com In addition to what Ajay wrote remember you can use AfxGetApp() to get at ...

Display differences Write-Host and Write-Warning
I'm new to PS, and a little embarrassed I can't find the answer to this on my own... I like to format text literals across multiple lines to manage the right margin of code text, but I'm having a problem with Write-Warning. There is apparently a significant difference in the way it handles its message text. Write-Host "Some literal text appended to" ` "some more text on the same line" Produces the desired output: Some literal text appended to some more text on the same line As you, PowerShellers, are aware, t...

Condition-clause in XSLT using .Net System.Xml
Hi. I'm trying to execute a simple <xsl:if>-clause with a condition that reads: a<1 In MSXML 4 the clause <xsl:if test="a &lt; 1">do something...</xsl:if> works fine. But in .Net Xml it just doesn't work. I can't use the real character (<) because the XSLT wont be a valid XML. And if I use the encoded representation (&lt;) it wont compute at all. Anybody got a clue what to do??? // Magus - Il Dottore Magus wrote: > I'm trying to execute a simple <xsl:if>-clause with a > condition that reads: a<1 > In MSXML ...

Write / Print Same Record
I have a subForm populated from a main form, but I only write the record if specific conditions are met. Once they are met though, I want the user to click a button on the subform and add the record and print that specific record at the same time. I was trying to use AddNewRec, but I can't do that because once they add the record that way, the subForm clears and the button gives an error message. Is there a way to update the table and print that same record? For example instead of an AddNewRecord, is there an UpdateTable or and UpdateNewRecord? Any help would be appreciated. -- ...

Sign Xml
Hi, I would like send an user a license certificate which is in xml file. It is ok that they can read it they are just not allowed to change it. I have tried to sign my xml document using the SignedXml class and the RSACryptoServiceProvider to create the key and that works fine. But I guess that the user just can remove the signed part, change the doucment and resign it. How can I check for that? The client is a consumer product which is beeing distributed to multiple locations. Thanks Henrik. Hi Henrik, The RSA algorith uses a key pair for encryption and signing. The SignedXml is d...

Guidance Software
Hello All, My name is Justin Giovinco and I am an IT Recruiter for Guidance Software, The World's Leader In Investigative Software. We currently have an urgent need for 2 developers in the Los Angeles area. The first developer is more of the hardware sort. We're looking for someone with solid experience designing and developing device drivers in a windows environment. This person should be well versed in C++, assembly language, and kernel development. Experience with SCSI, WinDbg, and SoftIce are all plus's. The second developer will be for our mobile device product. We are...

xml newbie question
We've have just reached a point where our program needs some type of Industry standard file format & XML seems the obvious choice Before I go rushing off and use the wrong system can anyone give a little advice Our files may be quite large but we will only use them for the - File-Open and File-Save options I am currently working in MFC but would like the opportunity to more to .NET later on I generally want to store human readable files but also some binary (bitmaps etc) We use the MFC serialisation which makes for easy programming but a hard life - is there an XML serialisatio...

How to use C# to write an xml document to MemoryStream, not a file?
I'm using XmlTextWriter now, but it seems it can just be used to create a xml file, how can I do? Thanks in advance! Jackfan Jackfan wrote: > I'm using XmlTextWriter now, but it seems it can just be used to create a > xml file, how can I do? MemoryStream ms = new MemoryStream(); XmlWriter w = new XmlTextWriter(ms, Encoding.UTF8); w.WriteStartDocument(); w.WriteElementString("foo", "", "bar"); w.WriteEndDocument(); w.Close(); -- Oleg Tkachenko [XML MVP] http://blog...

if System.IO.StreamWriter write throws an exception, is there anyway to close the System.IO.StreamWriter object? it seems to stay open when this happens then future attempts to write to that same path
if System.IO.StreamWriter write throws an exception, is there anyway to close the System.IO.StreamWriter object? it seems to stay open when this happens then future attempts to write to that same path fail because it says its in use by another process. Daniel wrote: > if System.IO.StreamWriter write throws an exception, is there anyway to > close the System.IO.StreamWriter object? it seems to stay open when this > happens then future attempts to write to that same path fail because it says > its in use by another process. The finally-block has been invented for this (untested):...

Integrate Collection Letters with Letter Writing Assistant
We suggest that there should be an integration between Collection Management letters with the Letter Writing Assistant. Some partners are looking for this integration as well. Thanks ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" in the message pane. http://www.microsoft.com/Businesssol...

Xml Validation Against Schema Facets
I know how to use the XmlReader to validate XML against a Schema but how do I take this one step further and get the Facet information for an invalid Xml element? I have my own validation event handler and I get the overall message about the problem but I need to report on what exactly the problem is. Does any know how to do this? Xml-Spy gives you the exact information but I need to do it programmatically with customers data and report errors. They want to know the exact error and right now I have to bring it into Xml-Spy and create a manual report. .Net has got to have something to do th...

How do we write a letter with office? It is too screwy to do so?
-- THANKS; "RHAB" <rexbahrex@hotmail.com> wrote in message news:44B2B719-5AAC-42E1-9195-62097C4DE77F@microsoft.com... > > -- > THANKS; Eh? Is this real or a wind up? If you can't figure out how to post a question that we can understand and respond with an intelligent answer, then yes. It will be too screwy for you to use. -- JoAnn Paules MVP Microsoft [Publisher] Tech Editor for "Microsoft Publisher 2007 For Dummies" "RHAB" <rexbahrex@hotmail.com> wrote in message news:44B2B719-5AAC-42E1-9195-62097...

Instantiating a structure array from XML in .net
Hey All, My app will have a structure array that will hold the parameters used to initialize a array of classes at run time to default values. XML looks like a good candidate to persist the data right? I'd like to have the XML file that persists the structure array. It would be nice to just initially author a XML file with my parameter values in it. It's a bit of a chicken/egg senerio. Is there any way to do this without first serializing the structure to get a XML 'template' file upon which to build? ...

Guidance on backup exchange server
Hello, I would like to have a second exchange server that is fully functional in the event our first exchange server is down. I am using exchange server 2003 on both servers. The primary DC is Small Business 2003, the backup dc is server 2003 standard. I would like to be able to take either one of the servers down at any time with no loss of email function. The servers have different names example server1.domain.local and server2.domain.local. I have myself and test users currently using second server, but I need to have all mailboxes on both servers. I have both exchange servers in sam...

CFont Guidance
As I am new to windows coding, could someone give me guidance on how to create a Font ( using CFont ) and then drawing some text to the screen? TIA CDC *pDC = GetDC(); CFont Font; //create a 12 point font; Font.CreatePointFont(120,"Arial"); CFont *pOldFont = pDC->SelectObject(&Font); pDC->DrawText(Text,Rect,DT_LEFT); pDC->SelectObject(pOldFont); ReleaseDC(pDC); AliR. "Golum256" <Golum256@discussions.microsoft.com> wrote in message news:DB2C617A-5F8F-406F-BA8F-120C49AD98E9@microsoft.com... > As I am new to windows coding, could someone give me gui...

.net xml editor doesn't recognize extension correctly
I am trying to use the xml desinger in .net 1.1 to create the follow schema. where USAddress is derived from Address But when I generate the xml file, the .net xml editor says "The active schema does not support the element 'street'" The schema is from a msdn .net example. What I am missing here? Thanks John Here are the xml file and xsd file: Here is the xml file: <?xml version="1.0" encoding="utf-8" ?> <xs:schema id="MySchema" targetNamespace="http://tempuri.org/MySchema.xsd" elementFormDefault="qualified"...

Write code to minimize to tray
I've searched for the documentation on this, and can't find it for some reason. How do you make an app minimize to the system tray? -Eric >I've searched for the documentation on this, and can't find it for some >reason. How do you make an app minimize to the system tray? Eric, Have a look at the Shell_NotifyIcon documentation. Unless your minimized application provides some visual notification mechanism to the user, you shouldn't use the tray notification area as a place to minimize your application window. Dave Yeah these api will work for you Shell_N...

XML Listener
I'm trying to create a 24/7 XML listener which will take any XML file or XLS file and send the data back and forth to SQL Server. This service has to run 24x7. Any suggestions! Thanks ...

reading an xml file by fragments
I have an Xml document containing the serialization of a very big arraylist. Each Item having any type. The file is big and I don't want to load it like this but by fragment of item. I made a try with XPathNavigator, but the Value property does not send me the result on the form of an Xml string. So I cant deserialized it with XmlSerializer. Is there a way to do this? thank you ...