我有这个结构:
<root>
<properties>
<property name="test">
<value>X</value>
</property>
</properties>
<things>
<thing>
<properties>
<property name="test">
<value>Y</value>
</property>
</properties>
</thing>
</things>
</root>
是否存在XPath表达式,如果以<root>
作为root运行,则选择仅值为X的test属性,如果以{{1}运行,则仅选择值为Y的值以root身份?
我认为thing
会要求它成为一个直接的孩子,但这似乎没有任何回报。如果我删除了斜杠,我会得到/properties/property[@name='test']
个元素(我使用的是C#,property
)。
答案 0 :(得分:2)
我认为您的意思是Property
而不是Properties
。试试./properties/property[@name='test']
答案 1 :(得分:2)
我认为
/properties/property[@name='test']
会要求它 是一个直接的孩子,但这似乎什么都没有。
以/
开头的任何XPath表达式都是绝对 XPath表达式 - 使用文档节点(/)作为初始上下文节点进行评估。
在你的情况下:
/属性/特性[@名称= '测试']
尝试选择名为properties
的顶级元素节点(然后是其子节点)并且这正确地选择没有节点,因为XML文档的顶部元素具有不同的名称 - root
。< / p>
你想要:
/root/properties/property[@name='test']
以下相对表达式是您希望在两种情况下都能使用的(具有初始上下文节点/root
和/root/things/thing
):
properties/property[@name='test']
答案 2 :(得分:1)
当您使用相对路径时,您正在使用绝对路径,这只能选择根目录下的路径;
string txt = @"<root><properties><property name=""test""><value>X</value></property></properties><things><thing><properties><property name=""test""><value>Y</value></property></properties></thing></things></root>";
var doc = XDocument.Parse(txt);
var root = doc.Root;
var val = root.XPathSelectElements("properties/property[@name='test']");