Vishal Sharnagat
Vishal Sharnagat

Reputation: 83

XSLT How to access attribute from different tag level?

I am new to xsl & xslt. I am using xslt for xml to xml conversion. I have below xml file. I am iterating through REQ-IF/record using for-each loop and inside the loop I want to iterate REQ-IF/Attributes/Attribute to access @Name value. I tried using ../ but it only gives one level up values and do not allow me to iterate. Could you please help me with this? Thanks.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<REQ-IF>
    <record>
        <Name>ABC</Name>
        <Presentationname>Task Record</Presentationname>
        <GUID>123</GUID>
    </record>
    <record>
        <Name>DEF</Name>
        <Presentationname>Role Record</Presentationname>
        <GUID>456</GUID>
    </record>
    <record>
        <Name>GHI</Name>
        <Presentationname>WorkProduct Record</Presentationname>
        <GUID>789</GUID>
    </record>
    <Attributes>
        <Attribute>
            <Name>Task</Name>
        </Attribute>
        <Attribute>
            <Name>Role</Name>
        </Attribute>
        <Attribute>
            <Name>WorkProduct</Name>
        </Attribute>
    </Attributes>
</REQ-IF>

Upvotes: 0

Views: 967

Answers (1)

Ilya Kharlamov
Ilya Kharlamov

Reputation: 3932

That works

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="/REQ-IF">
        <xsl:for-each select="record">
            <xsl:text>&#x0A;</xsl:text>
            <xsl:value-of select="./Name"/>
            <xsl:for-each select="../Attributes/Attribute">
                <xsl:text>&#x0A;&#x09;</xsl:text>
                <xsl:value-of select="Name"/>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

output:

ABC
    Task
    Role
    WorkProduct
DEF
    Task
    Role
    WorkProduct
GHI
    Task
    Role
    WorkProduct

In the nested loop you were probably using for-each select="../Attributes" instead of for-each select="../Attributes/Attribute". Since REQ-IF has only one Attributes node then there were only one result.

Upvotes: 2

Related Questions