tags:

views:

4075

answers:

5

I have an XmlDocument that already exists and is read from a file.

I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?

I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.

ex: Original XmlDoc:

<MyXml>
   <Employee>
   </Employee>
</MyXml>

and, I would like to add a Demographic (with several children) tag to Employee:

<MyXml>
   <Employee>
      <Demographic>
         <Age/>
         <DOB/>
      </Demographic>
   </Employee>
</MyXml>
+9  A: 

I suggest using XmlDocument.CreateDocumentFragment if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");

XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";

xdoc.DocumentElement.FirstChild.AppendChild(xfrag);
sixlettervariables
+3  A: 

Try this:

employeeNode.InnerXml = "<Demographic><Age/><DOB/></Demographic>";

Alternatively (if you have another XML document that you want to use):

employeeNode.AppendChild(employeeNode.OwnerDocument.ImportNode(otherXmlDocument.DocumentElement, true));
Panos
+1  A: 

Consider using an XmlWriter for building your fragments on a StringBuilder as this will provide validation and character substitution for you.

Jeff Yates
@ffpf: +1 good advice, but namespaces and XmlWriter always have me going back to MSDN.
sixlettervariables
A: 

As an alternative, this is how you could do it in a more LINQy 3.5 manner:

 XDocument doc = XDocument.Load(@"c:\temp\test.xml");
 XElement demoNode = new XElement("Demographic");
 demoNode.Add(new XElement("Age"));
 demoNode.Add(new XElement("DOB"));
 doc.Descendants("Employee").Single().Add(demoNode);
 doc.Save(@"c:\temp\test2.xml");
Echostorm
A: 

Hi,

All that I do is to create a new dataset object and open the xml file using ReadXML myDataset.ReadXML(path and file name).

Then add or remove the rows that I need and save the document again using myDataset.WriteXML(path and file name).

I'm sorry my english is not good.

Bye...