1

我在这里浏览了很多关于 SO 的示例,但我找不到我正在寻找的确切内容。有许多示例可以匹配具有特定父元素的元素。但是,我不想匹配特定的父母,我只想知道它是否有父母。

所以对于这里的xml:

<foo>
    <bar/>
</foo>
<bar/>

使用以下 XSLT:

<xsl:template match="bar">
    <xsl:choose>
        <xsl:when test="[test here]">
            ..do something..
        </xsl:when>
    </xsl:choose>
</xsl:template>

我如何简单地测试<bar>元素是否有父元素或没有?

谢谢!

4

2 回答 2

2

只需在父轴上使用通配符名称测试:test="parent::*"

于 2013-09-20T23:09:38.067 回答
2

这个输入:

<foo>
  <bar>
    <baz/>
  </bar>
</foo>

到这个脚本:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="*">

    <xsl:choose>
      <xsl:when test="parent::*">Parent: </xsl:when>
      <xsl:otherwise>No Parent: </xsl:otherwise>
    </xsl:choose>
    <xsl:value-of select="name()"/>
    <xsl:text>&#xa;</xsl:text>

    <xsl:apply-templates select="*"/>

  </xsl:template>

</xsl:stylesheet>

产生这个输出:

No Parent: foo
Parent: bar
Parent: baz

注意:您的示例输入文件格式不正确,不能用作 XSLT 转换的输入,因为它有两个根。

于 2013-09-21T00:02:40.063 回答