4

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

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
aharon
  • 7,393
  • 10
  • 38
  • 49

3 Answers3

3

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>
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I got the solution with the following code

var doc = XDocument.Load("C:\\Test.xml");
var DBID = doc.Root.Element("database").FirstAttribute.Name;
var DBIDValue = doc.Root.Element("database").FirstAttribute.Value;
utkumaden
  • 35
  • 1
  • 8
Lalita
  • 153
  • 2
  • 4
  • 16