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 -->

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="/">
      <TITLE>First XSLT Example</TITLE>
      <P><B>Invoice # </B>
        <xsl:value-of select="invoice/@num" />
        <B>     Invoice Date: </B>
        <xsl:value-of select="invoice/@invoiceDate" />

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

The key changes to this listing are the addition of

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


<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