检查XSL模板中的节点类型

hie*_*ppe 8 xslt xpath-1.0

是否可以检查我在同一模板中与模板匹配的节点类型?如果是的话,我该怎么办?例如,我想做这样的事情:

<xsl:template match="@*|node()">
    <xsl:choose>
        <xsl:when test="current() is an attribute">
        <!-- ... -->
        </xsl:when>
        <xsl:when test="current() is an element">
        <!-- ... -->
        </xsl:when>
        <xsl:otherwise>
        <!-- ... -->
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

Tim*_*m C 17

在这里看一下这个答案,因为这可以为您提供所需的信息:

区别:child :: node()和child ::*

这给出了以下xsl:选择测试所有节点,包括文档节点.

<xsl:choose>
  <xsl:when test="count(.|/)=1">
    <xsl:text>Root</xsl:text>
  </xsl:when>
  <xsl:when test="self::*">
    <xsl:text>Element </xsl:text>
    <xsl:value-of select="name()"/>
  </xsl:when>
  <xsl:when test="self::text()">
    <xsl:text>Text</xsl:text>
  </xsl:when>
  <xsl:when test="self::comment()">
    <xsl:text>Comment</xsl:text>
  </xsl:when>
  <xsl:when test="self::processing-instruction()">
    <xsl:text>PI</xsl:text>
  </xsl:when>
  <xsl:when test="count(.|../@*)=count(../@*)">
    <xsl:text>Attribute</xsl:text>
  </xsl:when>
</xsl:choose>
Run Code Online (Sandbox Code Playgroud)


Dim*_*hev 6

确定节点$node是否根节点的更精确方法:

not(count($node/ancestor::node()))
Run Code Online (Sandbox Code Playgroud)

TimC的答案中的表达式测试当前节点的类型:

count(.|/)=1
Run Code Online (Sandbox Code Playgroud)

但是当我们想要确定变量中节点的类型(可能属于另一个文档而不是当前文档)时,它不适用.

此外,测试命名空间节点:

count($node | $node/../namespace::*) = count($node/../namespace::*) 
Run Code Online (Sandbox Code Playgroud)


sha*_*piy 6

我强烈建议您使用XPath 2.0中引入的序列类型表达式.例如:

. instance of document-node()
. instance of element()
Run Code Online (Sandbox Code Playgroud)