检查节点的类型XSL模板(Check type of node in XSL template)

2019-07-17 17:51发布

是否可以检查我用相同的模板中的模板匹配一个节点的类型? 如果是这样,我该怎么办呢? 例如,我愿做这样的事情:

<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>

Answer 1:

看看这个答案在这里,因为这应该给你你需要的信息:

区别:子::节点()和儿童:: *

这给出了下面的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>


Answer 2:

确定更精确的方法,如果节点$node根节点

not(count($node/ancestor::node()))

在TimC的回答表达测试当前节点的类型:

count(.|/)=1

这可能属于另一个文件 - - 而不是当前文档,但是,当我们想确定一个变量节点的类型是不适用的情况。

此外,对于一个命名空间节点的测试

count($node | $node/../namespace::*) = count($node/../namespace::*) 


Answer 3:

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

. instance of document-node()
. instance of element()


文章来源: Check type of node in XSL template