Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to match attribute from another element and retrieve its content?

When I’m in : <xsl:template match="listOfPerson/person">

for person of id "A", is it possible to retrieve his information that is stored in another element here it’s inside the element data

xml :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<root>
    <data>
        <person id="A">
            <name> Anna </name>
            <age> 1 </age>
        </person>
        <person id="B">
            <name> Banana </name>
            <age> 1 </age>
        </person>
    </data>

    <listOfPerson>
        <person>
            <id>A</id>
        </person>
        <person>
            <id>B</id>
        </person>
    </listOfPerson>
</root>

my current xsl :

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" indent="yes" />
    <xsl:template match="root">
        <xsl:apply-templates select="listOfPerson/person"/>
    </xsl:template>
    <xsl:template match="listOfPerson/person">
        <xsl:value-of select="."/>
    </xsl:template>
</xsl:stylesheet>

current output :

A
B

desired output :

Anna 1
Banana 1

>Solution :

XSLT has a built-in key mechanism for resolving cross-references. Consider the following example:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:key name="person" match="data/person" use="@id" />

<xsl:template match="/root">
    <xsl:for-each select="listOfPerson/person">
        <xsl:variable name="data" select="key('person', id)" />
            <xsl:value-of select="$data/name" />
            <xsl:text> </xsl:text>
            <xsl:value-of select="$data/age" />
            <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Applied to your input example, the result will be:

 Anna   1 
 Banana   1 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading