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)?
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>
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With