XML Tutorials
  Home arrow XML Tutorials arrow Page 5 - Querying XML: Use Cases
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML TUTORIALS

Querying XML: Use Cases
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2008-02-14

    Table of Contents:
  • Querying XML: Use Cases
  • Use case SGML: Standard Generalized Markup Language.
  • Use case PARTS: recursive parts explosion.
  • Use case REF: queries based on references.
  • Further Discussion of the W3C XML Query-Use Cases in XSLT

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Querying XML: Use Cases - Further Discussion of the W3C XML Query-Use Cases in XSLT


    (Page 5 of 5 )

    XSLT 1.0

    Unlike most other examples in this book, this one is a smorgasbord of prepared meals. Querying XML can mean so many things that are difficult to come up with generic recipes. The W3C did a decent job classifying the kinds of queries that come up in various domains. The demonstration of these query solutions in XSLT should provide a sound base for approaching many types of query problems.

    Due to space considerations, this chapter did not include the XQuery solutions to the previous problems. Nevertheless, contrasting the two approaches is instructive, so I encourage the reader to examine the W3C Query Use Case document.

    Providing individual commentary on each query implemented earlier would be impractical. However, most readers with basic XSLT skills should have little trouble deciphering the solution. Many solutions shown have alternate solutions in XSLT. Some of the alternatives may actually be better than the ones in this chapter. My solutions were heavily influenced by the XQuery solution presented in the original W3C document. However, I also tried to vary the XSLT constructs used, sometimes favoring an iterative style (xsl:for-each) and other times using the declarative style provided by patterns and
    xsl:apply-templates.

    XSLT 2.0

    This chapter is quite large so I did not repeat all the solutions using 2.0. However, there are some select problems that illustrate the kinds of improvements one can achieve using the facilities of XPath 2.0 and XSLT 2.0:

    • Take advantage offor-each-groupor
      distinct-values()when you need to eliminate duplicates.

        Question 4. For each author in bib.xml, list the author's name and the titles of
      all books by that author, grouped inside a "result" element:

       
      <xsl:for-each-group select="//author" group-by="."> 
          <result>
           
      <xsl:copy-of select="."/> 
            <xsl:for-each select="/bib/book[author eq current-grouping-key()]"> 

              <xsl:copy-of
      select="title"/>
            </xsl:for-each>
          
      </result>
         </xsl:for-each-group> 


        
      <!-- Using distinct-values() -->

          
      <xsl:for-each select="distinct-values(//author)">
           
      <result>
             <xsl:copy-of select="."/> 
             <xsl:for-each select="/bib/book[author eq .]">
               
      <xsl:copy-of select="title"/>
            </xsl:for-each>
          </result>
        </xsl:for-each>
       
    • Avoid copying nodes by usingxsl:sequence.

         Question 8. In the document books.xml, find all section or chapter titles that
        contain the word "XML", regardless of the nesting level:

        <results>
        <xsl:sequence select="(//chapter | //section)/title)[contains(.,'XML')]"/>
        </results>
       
    • Take advantage of functions and sequences to simplify queries. 

        <?xml version="1.0"
      encoding="UTF-8"?>
        <xsl:stylesheet version="2.0"  
        xmlns:xsl="http://www.w3.org/1999/ XSL/Transform"  
        xmlns:xs="http://www.w3.org/2001/ XMLSchema"  
        xmlns:ckbk="http://www.ora.com/ XSLTCkbk">

       
      <xsl:key name="person-key" match="person" use="@name"/>

       
      <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

       
      <xsl:variable name="everyone" select="//person" as="item()*"/>

       
      <xsl:template match="census">
          <result>
            <xsl:apply-templates select="//person[@name='Joe']"/>
          </result>
        </xsl:template>

        
      <xsl:template match="person">

         
      <!--No need for node set conversions. Use descendants function directly -->
         
      <xsl:for-each select="ckbk:descendants(.,/)[current() != .]">
            <xsl:sort select="count(./* | $everyone[@name = current()/@spouse]/*)"
            order="descending" data-type="number"/>
            <xsl:sort select="@name"/>
            <xsl:variable name="mstatus" select="if (@spouse) then 'Yes' else 'No'"/>
            <person married="{$mstatus}"
       
                  nkids="{count(./* | key('person-key', @spouse)/*)}">
                  <xsl:value-of select="@name"/>
            </person>
          </xsl:for-each>
        </xsl:template>
       
      <!-- Note how this function is simpler than the template in the XSLT 1.0
        solution. We pass in the doc because it is unknown inside of functions.-->
        <xsl:function name="ckbk:descendants">
         
      <xsl:param name="nodes" as="item()*"/>
          <xsl:param name="doc"/>
          <xsl:sequence select="$nodes, for $person in $nodes return ckbk:descendants(
       
      ($person/person, key('person-key', $person/@spouse,$doc)/person), $doc)"/>
        </xsl:function>

       
      </xsl:stylesheet>

    See Also

    Evan Lenz has also explored the topic of using XSLT in place of XQuery (http:// xmlportfolio.com/xquery.html).

     


     

    * A mathematician will tell you that the intersection of a set with itself will always yield the same set. This is true for proper sets (with no duplicates). However, here you are using an application-specific notion of equality, and the node sets typically will not be proper sets under that equality test. However, the value-set operations always produce proper sets, so this technique is a way of removing duplicates.

    * It outputs both gender and sex attributes, but you knew that already!

    * These use cases were dropped from the latest version of the W3C document.

     


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This article is an excerpt from the "XSLT Cookbook, Second Edition," published by...
     

    Buy this book now. This article is excerpted from chapter nine of the XSLT Cookbook, Second Edition, written by Sal Mangano (O'Reilly; ISBN: 0596009747). Copyright © 2007 O'Reilly Media, Inc. Check it out today at your favorite bookstore. Buy this book now.

    XML TUTORIALS ARTICLES

    - Validation with Document Type Definitions (D...
    - Creating a Well-Formed XML Document
    - Creating XML Taxonomies
    - Getting to Know XML
    - A Friendly Approach to XML
    - Creating RSS 2.0 Feeds
    - Using Modules in Your RSS Feed
    - RSS 2.0
    - Querying XML: Use Cases
    - Joins and Query Use with XML
    - Solving Problems by Querying XML
    - Performing Set Operations When Querying XML
    - Querying XML
    - Handling Data for Ajax with JSON
    - Handling XML Data for Ajax





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek