xpath:测试节点是否是指定 OK 元素之外的唯一子元素



我想编写一个xsl模板,用于检查给定节点是否是唯一的子节点,除了某些指定的元素:

在此示例中,<目标 />将更改为<命中 />,因为它是唯一的<目标 />节点,并且只有节点位于它之前

<root>
<!-- this is ok, the ok nodes are at the top, followed by only 1 target -->
<mynode>
    <ok1/>
    <ok2/>
    <target/>
</mynode>
<!-- will fail, bad element before target -->
<mynode>
    <ok1/>
    <ok2/>
    <bad/>
    <target/>
</mynode>
<!-- no match, multiple target nodes -->
<mynode>
    <ok1/>
    <ok2/>
    <target/>
    <target/>
</mynode>
</root>

我正在使用这个 xpath:

<xsl:template match="target[not(following-sibling::*)]
                       [not(preceding-sibling::target)]
                       [not(preceding-sibling::*[starts-with(name(), 'bad' or 'hello')])]
                 ">
    <hit>
        <xsl:apply-templates/>
    </hit>
</xsl:template>

在最后一个谓词中,我是否必须特别指出我不想要的任何节点?我可以像这样吗

not(preceding-sibling::*[not(starts-with(name(), 'ok'))])

谢谢

这个怎么样:

<xsl:template match="target[count(../*) = 
                            count(../*[starts-with(name(), 'ok')]) + 1]">
    <hit>
        <xsl:apply-templates/>
    </hit>
</xsl:template>

解释是匹配target如果:

  • 其父元素的所有子元素的数量等于
  • 其父元素的所有良好子元素的数量加 1(本身)

编辑 如果您只想匹配元素,如果它是其父元素的最后一个子元素(您在问题中没有这么说,但您的示例表明了这一点),您可以在上面的谓词中添加and not(following-sibling::*),或者这里有另一种方法:

<xsl:template match="target[not(following-sibling::*) and 
                            not(preceding-sibling::*[not(starts-with(name(), 'ok'))])
                           ]">

但你似乎已经自己想通了。

最后,如果您实际想要做的是允许某些特定的 OK 元素并且不根据前缀匹配名称,则可以为此使用 self::

<xsl:template match="target[count(../*) = 
                            count(../*[self::allgood or self::great]) + 1]">
<xsl:template match="target[not(following-sibling::*) and 
                            not(preceding-sibling::*[not(self::allgood or
                                                         self::great     )]
                               )]">
[not(preceding-sibling::*[starts-with(name(), 'bad' or 'hello')])]

不会工作,因为"坏"或"你好"是布尔值或字符串你也不需要使用双 not()并且简单地做

preceding-sibling::*[starts-with(name(),'ok')]

您还可以创建白名单或黑名单,并使用 contains() XPath 函数对其进行迭代,例如:

<xsl:variable name="oks" select="ok1 ok2 ok3"/>

然后匹配

preceding-sibling::*[contains($oks, name())]

最新更新