mrB
mrB

Reputation: 15

XSLT save node attribute value into variable

How can I store attribute value in a variable?

XML example:

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

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

Desired output:

I want this

I have no clue how to do it. Please help

Upvotes: 0

Views: 851

Answers (1)

Rupesh_Kr
Rupesh_Kr

Reputation: 3435

Use

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

Instead of

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

or you can simply use it in xsl-value-of

    <xsl:if test="//DocumentVersion[@id]/DocumentType = $DOCTYPE_KEYWORD">
        <xsl:value-of select="//DocumentVersion[DocumentType = $DOCTYPE_KEYWORD]/Stuff"/>
    </xsl:if>

Upvotes: 1

Related Questions