Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Retrieving Attributes

Returning to the XML document instance in Listing 2.1, you'll notice that the <invoice> element contains two attributes; num and invoiceDate. To recap, the element looks like this:

<invoice num="2317" invoiceDate="07-09-01">
  <!-- ...other XML data -->
</invoice>

In this next style sheet, you would like to retrieve and display these attribute values in the browser window. Listing 2.5 shows the style sheet.

Listing 2.5 This Style Sheet Builds on the Previous by Retrieving the num and invoiceDate Attributes from the Source Document

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" />
  <!-- Root template -->
  <xsl:template match="/">
   <HTML>
     <HEAD>
      <TITLE>First XSLT Example</TITLE>
     </HEAD>
     <BODY>
      <P><B>Invoice # </B>
        <xsl:value-of select="invoice/@num" />
      </P>
      <P>
        <B>     Invoice Date: </B>
        <xsl:value-of select="invoice/@invoiceDate" />
      </P>
      <HR></HR>

      <P><B>Company: </B>
        <xsl:value-of select="invoice/clientName" />
      </P>
      <P><B>Contact: </B>
        <xsl:value-of select="invoice/contact" />
      </P>
      <P><B>Services Rendered: </B>
        <xsl:value-of select="invoice/descriptionOfServices" />
      </P>
      <P><B>Total Due: </B>
        $<xsl:value-of select="invoice/costOfServices" />
      </P>
     </BODY>
   </HTML>
  </xsl:template>
</xsl:stylesheet>

The key changes to this listing are the addition of

<xsl:value-of select="invoice/@num" />

and

<xsl:value-of select="invoice/@invoiceDate" />

Just as with retrieving the element content, you can grab the value of an attribute using <value-of>. As with element content, you must construct a step pattern and place it in the select attribute. In this case, the invoice element is the root element, so the first step specifies the invoice element. The second step contains the name of the attribute you want to retrieve prefixed by the @ character. Retrieving attribute values is that simple.

  • + Share This
  • 🔖 Save To Your Account