Search code examples
c#xmldocument

get grandson text using xml document in c#


I'm using XmlDocument in C# and I would like to know how to get grandson data of the root?

<tRoot>
   <One>
   <a>15</a>
   <b>11</b>
   <c>1</c>
   <d>11.35</d>
   <e>0</e>
   <f>289</f>
 </One>
 <Two>
   <a>0</a>
   <b>11</b>
   <c>1</c>
   <d>0.28</d>
   <e>0</e>
   <f>464</f>
</Two>
</tRoot>

and I want the ability to get a of One and also a of Two

I tried:

var doc = new XmlDocument();
doc.Load(Consts.FileConst);
var docXml = doc["One"];
if (docXml != null)
{
   float valFromXml = float.Parse(docXml["a"].InnerText);
}

The issue is that docXml is null

Any assitance?


Solution

  • As suggested above, XDocument would be a better alternative. If, however, you still want to use XmlDocument, you can iterate through the children using

    var doc = new XmlDocument();
    doc.Load(Consts.FileConst);
    foreach(XmlNode xmlNode in doc.DocumentElement.ChildNodes) {
      //access a/b/c/d/e using:          
      xmlNode.ChildNodes[0].InnerText; //for a
      xmlNode.ChildNodes[1].InnerText; //for b
    }