仅选择直系后代

本文关键字:后代 选择 | 更新日期: 2023-09-27 18:24:38

我有这样的结构:

<root>
  <properties>
    <property name="test">
      <value>X</value>
    </property>
  </properties>
  <things>
    <thing>
      <properties>
        <property name="test">
          <value>Y</value>
        </property>
      </properties>
    </thing>
  </things>
</root>

如果以<root>为根运行,是否有一个XPath表达式将仅选择值为X的测试属性,如果以thing为根运行则仅选择值为Y的测试属性?

我原以为/properties/property[@name='test']会要求它是一个直接的孩子,但这似乎没有任何回报。如果我去掉斜杠,我会得到两个property元素(我使用的是带有XElement root = ...; root.XPathSelectElements(xpathexpression);的C#)。

仅选择直系后代

我想你指的是Property而不是Properties。尝试./properties/property[@name='test']

我以为/properties/property[@name='test']会要求做一个直接的孩子,但这似乎没有任何回报。

任何以/开头的XPath表达式都是绝对XPath表达式——它是使用文档节点(/)作为初始上下文节点来计算的。

在您的情况下:

/properties/property[@name='test']

尝试选择一个名为properties的顶部元素节点(然后是它的子节点),但这正确地没有选择任何节点,因为XML文档的顶部元素有一个不同的名称——root

您想要

/root/properties/property[@name='test']

以下相对表达式是您希望在这两种情况下使用的(具有初始上下文节点/root/root/things/thing):

properties/property[@name='test']

当你应该使用相对路径时,你使用的是绝对路径,这只会选择根下的路径;

        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']");