Reputation: 189
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?
Upvotes: 3
Views: 3562
Reputation: 67
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text" indent="yes"/>
<xsl:key name="sss" match="section" use="reference"/>
<xsl:template match="root">
<xsl:for-each select="element">
<xsl:value-of select="key('sss', reference)/name"/>
<xsl:text> - </xsl:text>
<xsl:value-of select="price"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Upvotes: 2
Reputation: 117100
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>
Upvotes: 4
Reputation: 29052
Use two similar predicates on your XPath expressions. In this example a root node called <root>
is assumed to wrap the rest of your XML.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/root">
<xsl:value-of select="group/section[reference/text() = ../../element/reference/text()]/name" /> - <xsl:value-of select="element[reference/text() = ../group/section/reference/text()]/price" />
</xsl:template>
</xsl:stylesheet>
Output is:
<?xml version="1.0"?>
ABC - 20.00
Upvotes: -1