Creating documents over a subtree

After my TLC session on XML Tools in Visual Studio a gentleman came up to me and asked me a question. He said that he deals with XML coming over the pipe and their usually isn’t an end-of-file character at the end of his email document. He was trying to figure out how he can create a DOM over the valid XML. He was using one reader to do this. I knew that he could use the subtree reader but I didn’t have any code handy to give him. So I played around a bit and here is what I came up with:

 

public void TestSubTreeReader()

{

    XmlReaderSettings readerSettings = new XmlReaderSettings();

    readerSettings.ConformanceLevel =ConformanceLevel.Document;

   

    // this is the XML being used:

    /*

      <?xml version="1.0" encoding="utf-8" ?>

        <root>

          <a> </a>

          <b attribute="adkj">

            text 1

            <c> text 2 </c>

          </b>

          <d> text 3</d>

        </root>

        <outsideelement/>

     */

    string srcfile = @"sample.xml";

    XmlReader xReader =

      XmlReader.Create(srcfile, readerSettings);

    while (xReader.Read())

    {

        if (xReader.Name == "root")

        {

            XmlReader subTreeReader = xReader.ReadSubtree();

            XmlDocument doc = new XmlDocument();

      doc.Load(subTreeReader);

            return;

        }

    }

}

 

I approximated his scenario by using an XML file with two elements at the root level (which as we all know is not well-formed). I wanted to make sure that I create a DOM only on top of the “root” element.

 

In the while loop above I read the XML Declaration and eat it (I can see you wanting to use it for something interesting, but in my scenario, I do nothing with it). I then check to see if my reader is on the “root” node, if it is I create a new reader that is going to start at my root node and then read until it reaches the end root node.

 

I was worried that the subtree reader would not return the initial root node and would eat the end root node, but it doesn’t. The ReadSubtree() method returns a reader over the current node and all of it’s descendants.

 

So, there it is, I hope it helps.

 

Basking in the sun (or will be right after I post this) in beautiful Boston

Neetu Rajpal