Using XPath to parse an XML document

2020-03-09 05:06发布

Lets say I have the following xml (a quick example)

<rows>
   <row>
      <name>one</name>
   </row>
   <row>
      <name>two</name>
   </row>
</rows>

I am trying to parse this by using XmlDocument and XPath (ultimately so I can make a list of rows).

For example...

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

foreach(XmlNode row in doc.SelectNodes("//row"))
{
   string rowName = row.SelectSingleNode("//name").InnerText;
}

Why, within my foreach loop, is rowName always "one"? I am expecting it to be "one" on the first iteration and "two" on the second.

It seems that //name gets the first instance in the document, rather than the first instance in the row as I would expect. After all, I am calling the method on the "row" node. If this is "just how it works" then can anybody please explain how I could change it to work to my needs?

Thank you

7条回答
SAY GOODBYE
2楼-- · 2020-03-09 06:09

I would use SelectSingleNode, and then the InnerText property.

var rowName = row.SelectSingleNode("name").InnerText;
查看更多
登录 后发表回答