Luckily you don't have to create nodes then import them etc, instead the class XmlDocumentFragment comes to our rescue which allows us to write much cleaner code in this senario - and we all love clean code!
Take the following peice of XML file named myXml.xml:
<Sys>Now take the following code:
<Header\>
<Body\>
</Sys>
XmlDocument doc = new XmlDocument();Now take the following XML block:
doc.Load("myXml.xml");
<Start id="7672-2322-2322-3324"/>Now what if I wanted to add the above block of XML into the Body element of the doc XmlDocument object but I didn't have control over the schema -or maybe I don't care what the schema looks like or don't even know what it looks like, all I want to do is insert it into the body. I could use the CreateNode() method, but this is ugly and I have to know the schema, also this would add a maintance overhead as everytime the schema is changed, I'd have to change my code too.
Instead the XmlDocumentFragment class can be used. Take the following code:
XmlDocument doc = new XmlDocument();That is all there is too it. The output of the above will now look like the following:
string s = "<Start id="7672-2322-2322-3324"/>";
doc.Load("myXml.xml");
XmlDocumentFragment fragment = doc.CreateDocumentFragment();
fragment.InnerXml = s;
//Use GetElementsByTagName instead of XPath incase the schema changes.
XmlNodeList body = doc.GetElementsByTagName("Body");
if (body.Count > 0)
body[0].AppendChild(fragment);
<Sys>
<Header\>
<Body>
<Start id="7672-2322-2322-3324"/>
</Body>
</Sys>
No comments:
Post a Comment