简体   繁体   中英

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?

Try this:

XmlDocument d = new XmlDocument();
d.LoadXml("<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>");
XmlNodeList itemNodes = d.SelectNodes("//*/a");

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM