Andrew Hill
Andrew Hill

Reputation: 2253

Retrieve XML attribute value using XSLT

I have been tasked with building an XSLT file using a specific set of XML. The only problem is I have never used XSLT or XML. I have been digging through it for the last few hours and have hit my first real roadblock.

I need to return or print a value based on a given attribute in a specific XML node.

XML:

<Numbers>
    <Products productCode="RSD">
        <Value>54.99</Value>
        <Value>12.35</Value>
        <Value>8.00</Value>
        <Value>9.99</Value>
    </Products>
</Numbers>

I need my XSLT transform to produce a heading based on the productCode attribute (so that it can be placed in a table for better legibility). I am a JavaScript developer so in essence I am looking for the equivalent of

if(productCode === "RSD"){
    this.html("Product Heading");
}

I am completely out of my comfort zone here so any tips/pointers/advice is greatly appreciated.

Thank You!

Upvotes: 1

Views: 1342

Answers (1)

helderdarocha
helderdarocha

Reputation: 23627

If you apply your source XML to this stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output indent="yes"/>

    <xsl:template match="Products[@productCode='RSD']">
        <h1>Product Heading</h1>
        <table border='1'>
            <xsl:apply-templates select="Value"/>
        </table>
    </xsl:template>

    <xsl:template match="Value">
        <tr><td><xsl:value-of select="."/></td></tr>
    </xsl:template>

</xsl:stylesheet>

It will generate this HTML fragment:

<h1>Product Heading</h1>
<table border="1">
   <tr>
      <td>54.99</td>
   </tr>
   <tr>
      <td>12.35</td>
   </tr>
   <tr>
      <td>8.00</td>
   </tr>
   <tr>
      <td>9.99</td>
   </tr>
</table>

The first template uses an XPath expression to match the nodes you are interested in. The contents of the template describe the structure of your result tree. <xsl:apply-templates/> recursively processes the rest of the tree, and if it finds any matching templates it will process them. It uses a relative XPath expression Value to select the nodes named <Value> in the current context (which is <Product>), and will process all four of them. The second template matches that selection and generates the <tr><td> nodes. <xsl:value-of> simply prints the string-value of the nodes (the XPath expression . selects the node in the current context, which in the second template is <Value>.

You can verify and experiment with your example in this Fiddle

Upvotes: 1

Related Questions