XSLT-1.0可以使用变量来访问其他节点吗?

时间:2011-12-19 15:13:08

标签: variables expression nodes xslt-1.0

使用像这样的简单XML

<value>
    <num>
        <accession>111</accession>
        <sequence>AAA</sequence>
        <score>4000</score>
    </num>
</value>

我想知道是否可以从先前存储在变量中的节点访问特定节点。 XSLT代码很短,更好地解释了我想说的内容

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/value/num">
        <xsl:variable name="node">
            <xsl:copy-of select="current()"/>
        </xsl:variable>
        <root>
          <xsl:copy-of select="$node"/>
        </root>
    </xsl:template>
</xsl:stylesheet>

所以我将节点存储在变量“node”中。然后我可以使用$node打印节点的内容。

(EDIT)XML输出

<root>
    <num>
        <accession>111</accession>
        <sequence>AAA</sequence>
        <score>4000</score>
    </num>
</root>

我想要做的是打印子节点的内容,比如

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/value/num">
        <xsl:variable name="node">
            <xsl:copy-of select="current()"/>
        </xsl:variable>
        <root>
          <xsl:copy-of select="$node/accession"/>
        </root>
    </xsl:template>
</xsl:stylesheet>

但是它给出了一个错误(组件返回失败代码:0x80600008 [nsIXSLTProcessor.transformToFragment])(检查here

(编辑)我想要的XML是

<root>
    <accession>111</accession>
</root>

注意:问题不在于我如何获得此输出。问题是如何使用提供的XSLT中的变量来获取此输出。

(编辑:解决) 实际上它是可能的,但正如评论中所指出的,如果需要节点集,则必须使用“select”属性分配变量的值。所以这段代码没有用,因为变量有一个树片段而不是一个存储在其中的节点集(阅读更多信息here

谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/value">
        <root>
            <xsl:for-each select="num">
                <xsl:variable name="node" select="current()" />
                <xsl:copy-of select="$node/accession" />
           </xsl:for-each>
        </root>
    </xsl:template>
</xsl:transform>

请注意,我使用的是xsl:transform而不是xsl:stylesheet。此外,如果您有兼容的处理器,请考虑使用2.0版而不是1.0版,它会添加许多有用的功能。

但我仍然认为你不需要变量。