Friday, March 07, 2008

Adding a block of XML to an existing XmlDocument object

Sometimes you have the need to add a block of XML (string) to an existing XmlDocument (DOM object).

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>
<Header\>
<Body\>
</Sys>
Now take the following code:
XmlDocument doc = new XmlDocument();
doc.Load("myXml.xml");

Now take the following XML block:
<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();
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);
That is all there is too it. The output of the above will now look like the following:
<Sys>
<Header\>
<Body>
<Start id="7672-2322-2322-3324"/>
</Body>
</Sys>

No comments: