【问题标题】:Can XPath return only nodes that have a child of X?XPath 可以只返回具有 X 子节点的节点吗?
【发布时间】:2010-09-11 11:03:54
【问题描述】:

是否可以使用 XPath 仅选择具有特定子元素的节点?例如,从这个 XML 中,我只想要 pets 中具有“bar”子项的元素。因此,生成的数据集将包含此示例中的 lizardpig 元素:

<pets>
  <cat>
    <foo>don't care about this</foo>
  </cat>
  <dog>
   <foo>not this one either</foo>
  </dog>
  <lizard>
   <bar>lizard should be returned, because it has a child of bar</bar>
  </lizard>
  <pig>
   <bar>return pig, too</bar>
  </pig>
</pets>

这个 Xpath 给了我所有的宠物:"/pets/*",但我只想要有一个名为 'bar' 的子节点的宠物。

【问题讨论】:

  • 不要低估 w3c 规范的可读性和实用性。在w3.org/TR/xpath">the规范中查找此类问题的答案可能会更快,该规范非常易读且完整,有很多示例。

标签: xml xslt xpath


【解决方案1】:

它在它的所有荣耀中

/pets/*[bar]

英文:给我pets所有有孩子bar的孩子

【讨论】:

    【解决方案2】:
    /pets/child::*[child::bar]
    

    对不起,我没有看到之前的回复。

    但在这种情况下,我更喜欢使用 descendant:: 轴,它包括指定以下的所有元素:

    /pets[descendant::bar]
    

    【讨论】:

      【解决方案3】:

      以防万一您想更具体地了解孩子 - 您也可以对他们使用选择器。

      例子:

      <pets>
          <cat>
              <foo>don't care about this</foo>
          </cat>
          <dog>
              <foo>not this one either</foo>
          </dog>
          <lizard>
              <bar att="baz">lizard should be returned, because it has a child of bar</bar>
          </lizard>
          <pig>
              <bar>don't return pig - it has no att=bar </bar>
          </pig>
      </pets>
      

      现在,您只关心所有pets 是否有任何子bar 具有属性att 和值为baz。您可以使用以下 xpath 表达式:

      //pets/*[descendant::bar[@att='baz']]
      

      结果

      <lizard>
          <bar att="baz">lizard should be returned, because it has a child of bar</bar>
      </lizard>
      

      【讨论】:

      • 希望所有 元素具有特定文本()的宠物怎么样?好像我想不出来那个...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多