使用XPath解析XML文档 [英] Using XPath to parse an XML document

查看:59
本文介绍了使用XPath解析XML文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下xml(简单示例)

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

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

我试图通过使用XmlDocument和XPath来解析它(最终,我可以列出行).

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

例如...

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

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

为什么在我的foreach循环中,rowName总是一个"?我希望它在第一次迭代中为一个",而在第二次迭代中为两个".

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.

似乎//name获得了文档中的第一个实例,而不是我所期望的行中的第一个实例.毕竟,我要在行"节点上调用该方法.如果这只是它是如何工作的",那么任何人都可以解释一下如何更改它以满足我的需求吗?

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?

谢谢

推荐答案

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

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

您发布的代码是否正确?我在row.SelectNode()上收到编译错误,因为它不是XmlNode的成员.

Is the code you posted actually correct? I get a compile error on row.SelectNode() as it isn't a member of XmlNode.

无论如何,上面的示例都可以,但是假定< row> 节点内仅一个< name> 节点,因此您可能需要使用如果不是这种情况,请使用SelectNodes()代替 SelectSingleNode().

Anyway, my example above works, but assumes only a single <name> node within the <row> node so you may need to use SelectNodes() instead of SelectSingleNode() if that is not the case.

如其他人所示,使用 .InnerText 来获取值.

As others have shown, use .InnerText to get just the value.

这篇关于使用XPath解析XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆