简体   繁体   English

XML XPath - 仅在满足子条件时选择父文本

[英]XML XPath - selecting parent text only if child condition is met

I am working on a project that requires getting the text from a parent element without getting the text from the decedents only if the title attribute exists in the child element. 我正在开发一个项目,只有在子元素中存在title属性时才需要从父元素获取文本而不从死者获取文本。

In the example below, I need to get the text '1999' from the li element, if and only if, the title attribute exists in the child anchor ( li/i/a/@title ), is this possible? 在下面的例子中,我需要从li元素中获取文本'1999',当且仅当在子锚( li/i/a/@title )中存在title属性时,这可能吗? thanks in advance 提前致谢

This is what I tried initially, but this wont work for my use case... //ul/li/text()[last()] , also tried //ul/li/text() 这是我最初尝试过的,但这不适用于我的用例... //ul/li/text()[last()] ,也试过//ul/li/text()

<ul>
  <li>
      <i>
        <a href="#apples" title="apples">
          Apples
        </a>
      </i> (1999)
  </li>
</ul>

This XPath, 这个XPath,

//li[.//a/@title]/text()[last()]

will return the last text node child of those li elements with a descendant a that has a @title attribute: 将返回具有@title属性的后代a的那些li元素的最后一个文本节点子节点:

(1999)

as requested. 按照要求。

Credit : Simplified [.//a[@title]] to [.//a/@title] per helpful suggestion by Allan . 信用 :根据Allan的有用建议,简化[.//a[@title]][.//a/@title]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM