Search code examples
c#.netxmlreadxml

Reading an xml subtrees and the descendants C#


I have an XML file that contains several subTrees and those subtrees can also contain subtrees in them. something like this:

<File>
<A>...</A>
<B>...</B>
<C>
..
<D>..</D>
</C>
</File>

(The ".." are elements in the subtree). How can i read each subtree and then to reaad all its element (if this subtree containg a subtree i want to read it seperately and all his elements)?


Solution

  • XmlReader supports reading a subtree for that purpose; you can use the subtree-reader to as an input to other models (XmlDocument, XElement, etc) if you so wish:

    using(var reader = XmlReader.Create(source))
    {
        reader.MoveToContent();
        reader.ReadStartElement(); // <File>
        while(reader.NodeType != XmlNodeType.EndElement)
        {
            Console.WriteLine("subtree:");
            using(var subtree = reader.ReadSubtree())
            {
                while(subtree.Read())
                    Console.WriteLine(subtree.NodeType + ": " + subtree.Name);
            }
            reader.Read();
        }
        reader.ReadEndElement(); // </File>
    }