XPath和选择一个节点 [英] XPath and Selecting a single node

查看:176
本文介绍了XPath和选择一个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用XPath在.NET来解析XML文档,大致为:

I'm using XPath in .NET to parse an XML document, along the lines of:

XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");

foreach (XmlNode stuff in lotsOStuff)
{
   XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
   // ... etc
}

问题是,XPath查询对 stuffChild 总是返回的第一个的东西元素的孩子,从来没有其余的部分。可以XPATH不能用于对个人查询 XMLELEMENT

The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement?

推荐答案

// 在一个XPath EX pression年初开始从文档根目录。尝试.//stuffChild。 。是简写自::节点(),这将设置上下文的搜索,和//是简写后代轴

// at the beginning of an XPath expression starts from the document root. Try ".//stuffChild". . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.

所以,你有:

XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");

翻译过来就是:

which translates to:

<打击>的xmlNode stuffChild = stuff.SelectSingleNode(自::节点()/后裔:: stuffChild);

xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");

在那里的孩子节点可以有相同的名称作为父母的情况下,你会想用稍微详细的语法如下,以确保您不会重新选择父:

In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:

xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");

另外请注意,如果stuffChild是东西的直系后代,可以完全忽略prefixes,只是选择stuffChild。

Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".

XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");

借助 W3Schools的教程有一个简单有用的信息,以消化格式。

The W3Schools tutorial has helpful info in an easy to digest format.

这篇关于XPath和选择一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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