Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an xml subtrees and the descendants C#

Tags:

c#

.net

xml

readxml

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)?

like image 516
aharon Avatar asked Oct 26 '25 10:10

aharon


2 Answers

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>
}
like image 177
Marc Gravell Avatar answered Oct 27 '25 23:10

Marc Gravell


You could use a XDocument to read XML documents in .NET. For example to read the value of the D node:

var doc = XDocument.Load("test.xml");
var value = doc.Root.Element("C").Element("D").Value;
like image 30
Darin Dimitrov Avatar answered Oct 28 '25 00:10

Darin Dimitrov