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>
First load up a text field(you can put it to visible = false in public version) load the data in to the text field like so. string Path = Directory. GetCurrentDirectory() + "/2016"; string pathFile = Path + "/klanten. xml"; StreamReader sr = new StreamReader(pathFile); txt.
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.
LoadXml(String) Method.
The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).
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);
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));
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With