【问题标题】:Find element which has specific child element, but no text nodes查找具有特定子元素但没有文本节点的元素
【发布时间】:2018-05-28 19:30:55
【问题描述】:

对于 XSLT 模板,我需要一个针对具有特定子元素但没有文本节点的元素的 XPath 表达式。

<!-- 1: matches -->
<a><b/></a>

<!-- 2: does not match -->
<a>foo bar quux<b/></a>

<!-- 3: does not match -->
<a>whatever <b/> further text</a>

<!-- 4: does not match -->
<a>whatever <b/> further text <b/></a>

 <!-- 5: does not match -->
<a><x/><b/></a>

<!-- 6: does not match -->
<a>foo bar quux</a>

我想出了a[*[1 = last() and name() = 'b']],但是在不应该匹配的情况下,情况 2 或 3 被匹配了。原因当然是* 选择元素而不关心文本节点。那么我该怎么做呢?

【问题讨论】:

    标签: xslt xpath


    【解决方案1】:

    你可以使用

    a[count(*)=1 and b and not(text())]
    

    如果您只寻找一个 b,没有其他元素,也没有文本。请记住,如果您的 xml 中有回车符,某些处理器会将其视为文本。

    【讨论】:

    • 或者如果你可以接受多个b,a[b and not(*[name()!='b']) and not(text())]
    【解决方案2】:
    a[b and not(text() or *[2])]
    

    这会选择当前节点(上下文节点)的每个 a 子节点,其中包含 b 子节点,并且没有任何文本节点子节点或第二个元素子节点。

    如果您也不希望有任何 PI 或评论子项,您可以使用较短的版本:

    a[b and not(node()[2])]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2011-07-06
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多