0

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, I use your first solution because input XML is more complex and I want to do more complex stuff in XSL aswell. Also I've noticed that if statement is now redundand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.