Skip to main content

skip to main content

developerWorks  >  XML  >

XML for Data: What's new in XPath 2.0?

An early look at some of the planned features for XPath 2.0

developerWorks
Document options

Document options requiring JavaScript are not displayed


Rate this page

Help us improve this content


Level: Intermediate

Kevin Williams (kevin@blueoxide.com), CTO, Blue Oxide Technologies, LLC

01 Sep 2002

Kevin Williams takes a look at the latest status of the XPath 2.0 specifications and provides some specific examples of XPath 2.0 features that will make the XML developer's life easier. Examples are provided in XML and XPath.

XSLT 1.0 and XPath 1.0 were originally intended to provide simple style language support for XML documents, primarily to convert those documents into HTML for rendering to a browser. Since XSLT and XPath became available, however, they have been pressed into all sorts of tasks for which they weren't originally designed -- from the sophisticated manipulation of data in XML documents (aggregation, distinct selection, relationship pivoting) to XSLT's transformation of one XML form into another. In version 2.0 of these specifications, the W3C attempts to make XSLT and XPath much more flexible and robust in order to handle the new way these technologies are being used.

In the last column, I looked at some of the new features of XSLT. In this column, I will take a look at just a few highlights of XPath 2.0 -- there are far too many to mention in a single column.

For the purposes of this column, certain prefixes map to the following:

  • The xf: prefix is presumed to map to the XPath 2.0 functions namespace (http://www.w3.org/2002/08/xquery-functions).
  • The xsl: prefix maps to the XSLT 2.0 namespace.
  • The xs: prefix maps to the XML Schema namespace.

The xf:distinct-values function

One of the most significant challenges facing developers when working with XSLT 1.0 style sheets is to write the XML equivalent of a SELECT DISTINCT in SQL -- that is, an expression that takes a node set and returns a list of unique values from those nodes. This was not impossible in XSLT 1.0 and XPath 1.0, but fiendishly difficult. Basically, you had to write an xsl:for-each statement to evaluate each node in a particular sorted order, and then keep peeking back at the node list to see if any others matched the particular one being processed. With XSLT 2.0 and the introduction of the xf:distinct-values function, this problem goes away. Here's a quick example of the XML document in Listing 1:

<books>
  <book author="Kevin Williams" title="Professional XML 2.0" />
  <book author="Lewis Carroll" title="Alice in Wonderland" />
  <book author="Lewis Carroll" title="Through the Looking-Glass" />
</books>

Suppose you want to normalize out the author information and create a document that looks like Listing 2:

<authors>
  <author name="Kevin Williams">
    <book title="Professional XML 2.0" />
  </author>
  <author name="Lewis Carroll">
    <book title="Alice in Wonderland" />
    <book title="Through the Looking-Glass" />
  </author>
</authors>

To accomplish this, you need to do something like Listing 3 in XPath and XSLT 1.0:

<xsl:template match="books">
  <authors>
    <xsl:for-each select="book">
      <xsl:sort select="@author" />
      <xsl:variable name="thisAuthor">
        <xsl:value-of select="@author" />
      </xsl:variable>
      <xsl:if test="count(preceding-sibling::book)=0">
        <author name="{$thisAuthor}">
          <xsl:for-each select="../book[@author=$thisAuthor]">
            <book title="{@title}" />
          </xsl:for-each>
        </author>
      </xsl:if>
      <xsl:if test="preceding-sibling::book[1]/@author != $thisAuthor">
        <author name="{$thisAuthor}">
          <xsl:for-each select="../book[@author=$thisAuthor]">
            <book title="{@title}" />
          </xsl:for-each>
        </author>
      </xsl:if>
      </xsl:for-each>
    </authors>
</xsl:template>

A bit messy and difficult to document, however using xf:distinct, this becomes easy, as shown in Listing 4:

<xsl:template match="books">
  <authors>
    <xsl:for-each select="xf:distinct(book/@author)">
      <xsl:variable name="thisAuthor"><xsl:value-of select=".">
      <author name="{$thisAuthor}">
        <xsl:for-each select="book[@author=$thisAuthor]">
          <book title="{@title}" />
        </xsl:for-each>
      </author>
    </xsl:for-each>
  </authors>
</xsl:template>

How's this different from xsl:for-each-group? xf:distinct is available anywhere XPath is implemented -- so it is available as part of XQuery 1.0, as well as specialized XPath processors. With xf:distinct, you can perform other processing on the value set, as opposed to xsl:for-each-group, which forces the distinct values to be operated on individually.

This one change addresses many of the problems XSLT authors encounter when attempting to style documents. There are many other changes to XSLT that style sheet programmers will find useful.



Back to top


The xf:document function

Working with multiple documents can be problematic in XSLT 1.0. The designers of XPath 2.0 wisely chose to include additional document processing capability through the xf:document mechanism. This function allows one or more documents to be loaded from URLs and processed. For example, suppose you have the type of document shown in Listings 5, 6, and 7 in a repository:

<part name="Grommets" size="3 in." color="blue" />

<part name="Grommets" size="3 in." color="blue" />

<part name="Grommets" size="3 in." color="blue" />

Suppose you now have 500 of these documents in a single directory, and you want to create a list of all the blue parts you carry. Rather than writing code in a middle-tier language like Java to load each of these documents and look for parts with the color blue, you can write an index (see Listing 8) that lists where all the parts may be found:

<parts>
  <part file="part1.doc" />
  <part file="part2.doc" />
  <part file="part3.doc" />
</parts>

You can write a single style sheet that does the job for you with a fragment like the one in Listing 9:

<xsl:template match="parts">
  <blueParts>
    <xsl:for-each select="xf:document(part/@file)/@color='blue'">
      <part name={@name} size={@size} color={@color} />
    </xsl:for-each>
  </blueParts>
</xsl:template>

This technique lends itself particularly well to distributed networks of content, where the part information can be housed on one server and the customer information on another. Using style sheets that use xf:document to pull information from other URLs allows this data to live where it was created.



Back to top


The xf:current-dateTime function

When a style sheet is applied to an XML document, it is often helpful to include the creation date of the transformed result in the output. This is particularly important when creating HTML documents to drive a user interface; such information can help caching systems know when a copy of the information is stale. You can obtain the current date and time using the xf:current-dateTime function in XPath 2.0 (see Listing 10):

<xsl:value-of select="xf:current-dateTime()" />

This might return the string shown in Listing 11:

2002-09-17T18:22:08z

You can then use this string as-is or transform it into a different date format for use in the resulting document.



Back to top


Better XML Schema compatibility

Since XPath 2.0 is now being shared between XSLT 2.0 and XQuery 1.0, it follows that XPath would need more robust support for XML Schema. Indeed, the entire data model in XPath 2.0 is now strongly typed: Rather than having simple string, number, and boolean types, values now use the primitives defined as part of the XML Schema specification. A full set of functions is provided so you can explicitly convert these values from one type to another as part of their manipulation in XPath 2.0. For example, a value can be cast to another type by using the type name as if it were a function. So you could cast a value to an unsigned integer using the code fragment in Listing 12:

xs:unsignedInt(item)

The strong typing in XPath 2.0 ensures that a document created by an XSLT style sheet can be validated against a strongly-typed XML schema. Before XSLT 2.0, there was no way to guarantee, for example, that a number was an unsigned integer -- the XML Schema validation step was necessary to ensure that a faulty value was not provided by the style sheet.

In this document, I've just touched on the highlights of what XPath 2.0 has to offer. While this technology is still a good ways from being promoted to recommendation status (at least six months), familiarizing yourself with XPath 2.0's features and functionality will prepare you to take full advantage of it when implementations start to emerge.



Resources



About the author

Kevin Williams is the CTO of Blue Oxide Technologies, LLC, a company that designs XML and XML Web service design software. Visit their Web site at http://www.blueoxide.com. He can be reached for comment at kevin@blueoxide.com.




Rate this page


Please take a moment to complete this form to help us better serve you.



YesNoDon't know
 


 


12345
Not
useful
Extremely
useful
 


Back to top