Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: How to find value of the node by another node

Tags:

xml

xslt

I am not sure I am asking the question correctly, that's why I cannot find an answer anywhere. But basically I need to match a node with another node and use a sibling node as a value instead. Here is an example

<group>
    <section>
      <reference>123</reference>
      <name>ABC</name>
    </section>
    <section>
      <reference>456</reference>
      <name>DEF</name>
   </section>
</group>
<element>
   <reference>123</reference>
   <price>20.00</price>
</element>

And in my XSL template I want to display Price and Name, so I need to match Reference from the Element to Reference in Section and display Name.

ABC - 20.00

How can I do this?

like image 287
yennefer Avatar asked Dec 13 '25 13:12

yennefer


1 Answers

I need to match Reference from the Element to Reference in Section and display Name.

XSLT has a special feature called key just for this purpose. For example, the following stylesheet:

XSLT 1.0

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

<xsl:key name="section" match="section" use="reference" />

<xsl:template match="/root">
    <output>
        <xsl:for-each select="element">
            <item>
                <xsl:value-of select="key('section', reference)/name"/>
                <xsl:text> - </xsl:text>
                <xsl:value-of select="price"/>      
            </item>
        </xsl:for-each> 
    </output>
</xsl:template>

</xsl:stylesheet>

when applied to the following well-formed input:

XML

<root>
  <group>
    <section>
      <reference>123</reference>
      <name>ABC</name>
    </section>
    <section>
      <reference>456</reference>
      <name>DEF</name>
    </section>
  </group>
  <element>
    <reference>123</reference>
    <price>20.00</price>
  </element>
</root>

will return:

Result

<?xml version="1.0" encoding="UTF-8"?>
<output>
   <item>ABC - 20.00</item>
</output>
like image 69
michael.hor257k Avatar answered Dec 15 '25 17:12

michael.hor257k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!