XSLT将节点属性值保存到变量中

时间:2018-04-19 11:25:01

标签: xslt

如何将属性值存储在变量中?

XML示例:

<sth:mainNode>
    <DocumentVersion id="01">
        <DocumentType>Type1</DocumentType>
        <Stuff>I want this</Stuff>
    </DocumentVersion>
    <DocumentVersion id="02">
        <DocumentType>Type2</DocumentType>
        <Stuff>I dont want this</Stuff>
    </DocumentVersion>
</sth:mainNode>

XSL示例:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            version="1.0" xmlns:xsk="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" omit-xml-declaration="yes" indent="no" media-type="string"/>
    <xsl:variable name="DOCTYPE_KEYWORD" select="'Type1'"/>
    <xsl:template match="/">
        <xsl:if test="//DocumentVersion[@id]/DocumentType = $DOCTYPE_KEYWORD">
            <xsl:variable name="docVersionID" select="@id"/>
            <xsl:value-of select="//DocumentVersion[@id=$docVersionID]/Stuff"/>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

期望的输出:

I want this

我不知道怎么做。请帮忙

1 个答案:

答案 0 :(得分:1)

使用

<xsl:variable name="docVersionID" select="//DocumentVersion[DocumentType = $DOCTYPE_KEYWORD]/@id"/>

而不是

<xsl:variable name="docVersionID" select="@id"/>

或者您只需在xsl-value-of

中使用它即可
    <xsl:if test="//DocumentVersion[@id]/DocumentType = $DOCTYPE_KEYWORD">
        <xsl:value-of select="//DocumentVersion[DocumentType = $DOCTYPE_KEYWORD]/Stuff"/>
    </xsl:if>