XPath tutorial - basics: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
Line 254: Line 254:
  @val
  @val


==== Find attributes of an element in a longer location path starting from root ====
; Find attributes of an element in a longer location path starting from root


'' /element_name/element_name/@attribute_name''
''/element_name/element_name/@attribute_name''


Example:
Example:
  /project/problems/solutions/item/@val
  /project/problems/solutions/item/@val


 
; Find attributes in the whole document:
 
==== Find attributes in the whole document ====
 
'' //@attribute_name''
'' //@attribute_name''


==== Example 2-2: Make an html img link from an attribute ====
==== Example 2-2: Make an html img link from an attribute ====


;XML fragment
;XML fragment
 
Same as above
<participants>
 
  <participant>
 
    <FirstName>Daniel</FirstName>
 
    <qualification>8</qualification>
 
    <description>Daniel will be the tutor</description>
 
    <FoodPref picture="dolores_001.jpg">Sea Food</FoodPref>
 
  </participant>
 
  <participant>
 
    <FirstName>Jonathan</FirstName>
 
    <qualification>5</qualification>
 
    <FoodPref picture="dolores_002.jpg">Asian</FoodPref>
 
  </participant>
 
  <participant>
 
    <FirstName>Bernadette</FirstName>
 
    <qualification>8</qualification>
 
    <description>Bernadette is an arts major</description>
 
  </participant>
 
  .......
 
 


;Task
;Task
 
Display a list of First Names plus their food preferences
* Display a list of First Names plus their food preferences
 
 


;XSLT (File xpath-jungle-2.xsl)
;XSLT (File xpath-jungle-2.xsl)


* The first rule will just select all participants and create the list container (ul)
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
  &lt;xsl:template match="/"&gt;
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 
                version="1.0">
    &lt;html&gt;
 
      &lt;body bgcolor="#FFFFFF"&gt;
 
        &lt;h1&gt;What do we know about our participants ?&lt;/h1&gt;
 
        Here are some food preferences:


''        &lt;ul&gt;''
  <xsl:output method="html"/>


        &lt;xsl:apply-templates select=''".//participant"''
  <xsl:template match="/">
   /&gt;
    <html>
      <body bgcolor="#FFFFFF">
        <h1>What do we know about our participants ?</h1>
        Here are some food preferences: <ul>
        <xsl:apply-templates select=".//participant" />
      </ul>
      </body>
    </html>
   </xsl:template>


      ''  &lt;/ul&gt;''
<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/>
  <xsl:apply-templates select="FoodPref"/>
  </li>
</xsl:template>


      &lt;/body&gt;
<xsl:template match="FoodPref">
  prefers <xsl:value-of select="."/>.
  <img src="{@picture}"/> <br clear="all"/>
</xsl:template>


    &lt;/html&gt;
</xsl:stylesheet>


  &lt;/xsl:template&gt;
</pre>


* The second rule will display names of participants and launch a template for FoodPref
* The second rule will display names of participants and launch a template for FoodPref
* Note: Not all participants have a FoodPref element. If it is absent it will just be ignored.
* Note: Not all participants have a FoodPref element. If it is absent it will just be ignored.
 
* The third rule (FoodPref) displays the text (contents) of FoodPref and then makes an HTML img tag
&lt;xsl:template match="participant"&gt;
 
  &lt;li&gt;&lt;xsl:value-of select="''FirstName''
"/&gt;
 
  &lt;xsl:apply-templates select="''FoodPref''
"/&gt;
 
  &lt;/li&gt;
 
&lt;/xsl:template&gt;
 
* This rule displays the text (contents) of FoodPref and then makes an HTML img tag
 
&lt;xsl:template match="FoodPref"&gt;
 
  prefers &lt;xsl:value-of select=''"."''
/&gt;.
 
  &lt;img src="''{@picture}''
"/&gt; &lt;br clear="all"/&gt;
 
&lt;/xsl:template&gt;
 




;Parts of the result:
;Parts of the result:
   &lt;h1&gt;What do we know about our participants ?&lt;/h1&gt;
   &lt;h1&gt;What do we know about our participants ?&lt;/h1&gt;
       Here are some food preferences:
       Here are some food preferences:
       &lt;ul&gt;
       &lt;ul&gt;
           &lt;li&gt;Daniel prefers Sea Food.
           &lt;li&gt;Daniel prefers Sea Food.
             &lt;img src="dolores_001.jpg"&gt;&lt;br clear="all"&gt;&lt;/li&gt;
             &lt;img src="dolores_001.jpg"&gt;&lt;br clear="all"&gt;&lt;/li&gt;
           &lt;li&gt;Jonathan
           &lt;li&gt;Jonathan
             prefers Asian.
             prefers Asian.
             &lt;img src="dolores_002.jpg"&gt;&lt;br clear="all"&gt;&lt;/li&gt;
             &lt;img src="dolores_002.jpg"&gt;&lt;br clear="all"&gt;&lt;/li&gt;
           &lt;li&gt;Bernadette&lt;/li&gt;
           &lt;li&gt;Bernadette&lt;/li&gt;
           &lt;li&gt;Nathalie&lt;/li&gt;
           &lt;li&gt;Nathalie&lt;/li&gt;
       &lt;/ul&gt;
       &lt;/ul&gt;


 
=== Location wildcards ===
 
=== 2.5 Location wildcards ===


* Sometimes (but not often!), it is useful to work with wildcards
* Sometimes (but not often!), it is useful to work with wildcards
* You have to understand that only '' one'' rule will be applied/element. Rules with wildcards have less priority and this is why "your rules" are applied before the system defaults.
* You have to understand that only '' one'' rule will be applied/element. Rules with wildcards have less priority and this is why "your rules" are applied before the system defaults.


 
; Find all child nodes of type XML element
 
==== Find all child nodes of type XML element ====
 
'' *''
'' *''


 
; Find all child nodes (including comments, etc.)
 
==== Find all child nodes (including comments, etc.) ====
 
'' node()''
'' node()''


 
; Find all element attributes
 
==== Find all element attributes ====
 
'' @*''
'' @*''


 
; Find all text nodes
 
''text()''
==== Find all text nodes ====
 
text()
 
 


;FYI: The system built-in (default) rules rely on wildcards
;FYI: The system built-in (default) rules rely on wildcards


This rule applies to the document root and all other elements (see [xml-xpath.html#23299 2.8 ���%G�₁��%@���Union of XPaths���%G�₁��%@ [25]])
This rule applies to the document root and all other elementsn
 
  &lt;xsl:template match="*|/"&gt;
  &lt;xsl:template match="*|/"&gt;
   &lt;xsl:apply-templates/&gt;
   &lt;xsl:apply-templates/&gt;
  &lt;/xsl:template&gt;
  &lt;/xsl:template&gt;


Text and attribute values are just copied (see
Text and attribute values are just copied (see
  &lt;xsl:template match="text()|@*"&gt;
  &lt;xsl:template match="text()|@*"&gt;
   &lt;xsl:value-of select="."/&gt;
   &lt;xsl:value-of select="."/&gt;
  &lt;/xsl:template&gt;
  &lt;/xsl:template&gt;


 
=== XPaths with predicates ===
 
=== 2.6 XPaths with predicates ===


* A predicate is an '' expression that can be true or false''
* A predicate is an '' expression that can be true or false''
Line 460: Line 361:
* Expressions can contain mathematical or boolean operators
* Expressions can contain mathematical or boolean operators


 
; Find element number N in a list
 
==== Find element number N in a list ====


'' XML_element_name '' '' [ N ]''
'' XML_element_name '' '' [ N ]''


  /project/participants/participant''[2]''
  /project/participants/participant''[2]''
/project/participants/participant''[2]''/FirstName


/project/participants/participant''[2]''
; Find elements that have a given attribute
/FirstName
 
 
 
==== Find elements that have a given attribute ====


'' XML_element_name [ @attribute_name ]''
'' XML_element_name [ @attribute_name ]''


; Find elements that have a given element as child


 
'' XML_element_name [ XML_element_name ]''//participant[FoodPref]
==== Find elements that have a given element as child ====
 
'' XML_element_name [ XML_element_name ]''
 
//participant[FoodPref]
 
 


;Mathematical expressions
;Mathematical expressions


* Use the standard operators, except '' div'' instead of'' /'' ")
* Use the standard operators, except '' div'' instead of'' /'' ")
 
- * div mod
- * div mod


* mod is interesting if you want to display a long list in table format
* mod is interesting if you want to display a long list in table format
 
5 mod 2 returns 1, "7 mod 2" and "3 mod 2" too
5 mod 2 returns 1, "7 mod 2" and "3 mod 2" too
 
 


;Boolean operators (comparison, and, or)
;Boolean operators (comparison, and, or)


* List of operators (according to precedence)
* List of operators (according to precedence)
 
&lt;=, &lt;, &gt;=, &gt;
&lt;=, &lt;, &gt;=, &gt;
=, !=
 
and, or
<nowiki>=, !=</nowiki>
 
and
 
or
 




Line 516: Line 395:


* Return all exercise titles with a grade bigger than 5.
* Return all exercise titles with a grade bigger than 5.
//exercise[note&gt;5]/title
//exercise[note&gt;5]/title


* Find elements that have a given attribute with a given value
* Find elements that have a given attribute with a given value
'' XML_element_name [ @attribute_name = 'value']''
'' XML_element_name [ @attribute_name = 'value']''
  //solutions/item''[@val="low"]''
  //solutions/item''[@val="low"]''
'' ''


* Example XSLT template that will match all item elements with val="low".
* Example XSLT template that will match all item elements with val="low".


&lt;xsl:template match="'' //item[@val='low']'' "&gt;
&lt;xsl:template match="'' //item[@val='low']'' "&gt;
 
    &lt;xsl:value-of select="." /&gt;
&lt;xsl:value-of select="." /&gt;
&lt;/xsl:template&gt;
 
;Note: Usually expressions also contain functions
&lt;/xsl:template&gt;
 
 
 
;Note: Usually expression also contain functions (see [xml-xpath.html#21068 2.7 ���%G�₁��%@���XPath functions���%G�₁��%@ [21]])


* Return last five elements of a list
* Return last five elements of a list
  author [(last() - 4) &lt;= position()) and (position() &lt;= last())]
  author [(last() - 4) &lt;= position()) and (position() &lt;= last())]


* Return all '' Participant'' nodes with a contents of '' FirstName'' bigger than 7 characters:
* Return all '' Participant'' nodes with a contents of '' FirstName'' bigger than 7 characters:
  "//Participant[string-length(FirstName)&gt;=8]"
  "//Participant[string-length(FirstName)&gt;=8]"


==== Example 2-3: Retrieve selected elements ====
==== Example 2-3: Retrieve selected elements ====


;The XSLT stylesheet (file xpath-jungle-3.xsl)
;The XSLT stylesheet (file xpath-jungle-3.xsl)


&lt;xsl:template match="/"&gt;
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
  &lt;html&gt;
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 
                version="1.0">
    &lt;body bgcolor="#FFFFFF"&gt;
 
      &lt;h1&gt;Retrieve selected elements&lt;/h1&gt;
 
      ''Here is the name of participant two: ''
 
        &lt;ul&gt;&lt;li&gt;&lt;xsl:value-of select="''.//participant[2]/FirstName''
"/&gt;&lt;/li&gt;&lt;/ul&gt;
 
      ''Here are all participant's firstnames that have a food preference:''
 
      &lt;ul&gt;&lt;xsl:apply-templates select="''.//participant[FoodPref]''
"/&gt;&lt;/ul&gt;
 
      ''Here are all items that have a value of "high"''


      &lt;ul&gt;&lt;xsl:apply-templates select="''.//item[@val='high']''
  <xsl:output method="html"/>
"/&gt;&lt;/ul&gt;


    &lt;/body&gt;
  <xsl:template match="/">
 
    <html>
  &lt;/html&gt;
      <body bgcolor="#FFFFFF">
 
        <h1>What do we know about our participants ?</h1>
&lt;/xsl:template&gt;
        Here are some food preferences: <ul>
 
        <xsl:apply-templates select=".//participant" />
��
      </ul>
 
      </body>
&lt;xsl:template match="participant"&gt;
    </html>
 
  </xsl:template>
  &lt;li&gt;&lt;xsl:value-of select="FirstName"/&gt;&lt;/li&gt;
 
&lt;/xsl:template&gt;
 
��
 
&lt;xsl:template match="item"&gt;
 
  &lt;li&gt;&lt;xsl:value-of select="."/&gt;&lt;/li&gt;
 
&lt;/xsl:template&gt;


��
<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/>
  <xsl:apply-templates select="FoodPref"/>
  </li>
</xsl:template>


<xsl:template match="FoodPref">
  prefers <xsl:value-of select="."/>.
  <img src="{@picture}"/> <br clear="all"/>
</xsl:template>


</xsl:stylesheet>
</pre>


;HTML result
;HTML result


  &lt;html&gt;
  &lt;html&gt;
     &lt;body bgcolor="#FFFFFF"&gt;
     &lt;body bgcolor="#FFFFFF"&gt;
       &lt;h1&gt;Retrieve selected elements&lt;/h1&gt;
       &lt;h1&gt;Retrieve selected elements&lt;/h1&gt;
       Here is the name of participant two:
       Here is the name of participant two:
       &lt;ul&gt;
       &lt;ul&gt;
           &lt;li&gt;Jonathan&lt;/li&gt;
           &lt;li&gt;Jonathan&lt;/li&gt;
       &lt;/ul&gt;
       &lt;/ul&gt;
       Here are all participant's firstnames that have a food preference:
       Here are all participant's firstnames that have a food preference:
       &lt;ul&gt;
       &lt;ul&gt;
           &lt;li&gt;Daniel&lt;/li&gt;
           &lt;li&gt;Daniel&lt;/li&gt;
           &lt;li&gt;Jonathan&lt;/li&gt;
           &lt;li&gt;Jonathan&lt;/li&gt;
       &lt;/ul&gt;
       &lt;/ul&gt;
       Here are all items that have a value of "high"
       Here are all items that have a value of "high"
       &lt;ul&gt;
       &lt;ul&gt;
           &lt;li&gt;Register for a XSLT course and do exercices&lt;/li&gt;
           &lt;li&gt;Register for a XSLT course and do exercices&lt;/li&gt;
           &lt;li&gt;Register for a XPath course and do exercices&lt;/li&gt;
           &lt;li&gt;Register for a XPath course and do exercices&lt;/li&gt;
       &lt;/ul&gt;
       &lt;/ul&gt;
     &lt;/body&gt;
     &lt;/body&gt;
  &lt;/html&gt;
  &lt;/html&gt;


 
=== XPath functions ===
 
=== 2.7 XPath functions ===


* XPath defines a certain number of functions
* XPath defines a certain number of functions
Line 661: Line 484:
* There are restrictions on how you can use functions (stick to examples or the reference)
* There are restrictions on how you can use functions (stick to examples or the reference)


 
; last()
 
==== last() ====


last() gives the number or nodes within a context
last() gives the number or nodes within a context


 
; position()
 
==== position() ====


position() returns the position of an element with respect to other children for a parent
position() returns the position of an element with respect to other children for a parent


 
; count(node-set)
 
==== count(node-set) ====
 
count gives the number of nodes in a node set (usually found with an XPath).
count gives the number of nodes in a node set (usually found with an XPath).


 
; starts-with(string, string)
 
==== starts-with(string, string) ====


returns TRUE if the second string is part of the first and starts off the first
returns TRUE if the second string is part of the first and starts off the first


//Participant[starts-with(Firstname,'Berna')]"
//Participant[starts-with(Firstname,'Berna')]"
 


 
; contains(string, string)
==== contains(string, string) ====


returns TRUE if the second string is part of the first
returns TRUE if the second string is part of the first


//Participant[contains(FirstName,'nat')]
//Participant[contains(FirstName,'nat')]
 
 


==== string-length(string) ====
; string-length(string)


returns the length of a string
returns the length of a string


 
; number(string)
 
==== number(string) ====


transforms a string into a number
transforms a string into a number


 
; sum(node-set)
 
==== sum(node-set) ====


computes the sum of a given set of nodes. <br /> If necessary, does string conversion with number()
computes the sum of a given set of nodes. <br /> If necessary, does string conversion with number()


 
; round(number)
 
==== round(number) ====


round a number, e.g. 1.4 becomes 1 and 1.7 becomes 2
round a number, e.g. 1.4 becomes 1 and 1.7 becomes 2


 
; translate(string1, string2, string3)
 
==== translate(string1, string2, string3) ====


translates string1 by substituting string2 elements with string3 elements
translates string1 by substituting string2 elements with string3 elements
(See next slides for examples ....)


==== Example 2-4: Computation of an average ====
==== Example 2-4: Computation of an average ====
Line 734: Line 532:


  &lt;participant&gt;&lt;FirstName&gt;Daniel&lt;/FirstName&gt;
  &lt;participant&gt;&lt;FirstName&gt;Daniel&lt;/FirstName&gt;
               ''&lt;qualification&gt;8&lt;/qualification&gt;''
               ''&lt;qualification&gt;8&lt;/qualification&gt;''
     &lt;/participant&gt;
     &lt;/participant&gt;


;The XSLT stylesheet (file xpath-jungle-4.xsl)
;The XSLT stylesheet (file xpath-jungle-4.xsl)
Line 744: Line 539:
* We compute the sum of a node-set and then divide by the number of nodes
* We compute the sum of a node-set and then divide by the number of nodes


&lt;xsl:template match="/"&gt;
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
    &lt;html&gt;
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 
                version="1.0">
      &lt;body bgcolor="#FFFFFF"&gt;
 
        &lt;h1&gt;Qualification level of participants&lt;/h1&gt;
 
        Average is
 
        '' &lt;xsl:value-of select=''
''"sum(.//participant/qualification) div ''
 
''                              count(.//participant/qualification)"''
''/&gt;''
 
      &lt;/body&gt;
 
    &lt;/html&gt;
 
  &lt;/xsl:template&gt;


  <xsl:output method="html"/>


  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>Qualification level of participants</h1>
        Average is
        <xsl:value-of select="sum(.//participant/qualification) div count(.//participant/qualification)"/>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
</pre>


;HTML result
;HTML result
  &lt;html&gt;
  &lt;html&gt;
     &lt;body bgcolor="#FFFFFF"&gt;
     &lt;body bgcolor="#FFFFFF"&gt;
       &lt;h1&gt;Qualification level of participants&lt;/h1&gt;
       &lt;h1&gt;Qualification level of participants&lt;/h1&gt;
       Average is
       Average is
       5.75
       5.75
     &lt;/body&gt;
     &lt;/body&gt;
  &lt;/html&gt;
  &lt;/html&gt;


==== Example 2-5: Find first names containing 'nat' ====
==== Example 2-5: Find first names containing 'nat' ====


;The XSLT stylesheet (file xpath-jungle-5.xsl)
;The XSLT stylesheet (file xpath-jungle-5.xsl)


&lt;xsl:template match="/"&gt;
<pre>
 
<?xml version="1.0" encoding="utf-8"?>
  &lt;html&gt;
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">


  &lt;body bgcolor="#FFFFFF"&gt;
  <xsl:output method="html"/>


  &lt;h1&gt;Do we have a "nat" ?&lt;/h1&gt;
  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>Do we have a "nat" ?</h1>
        First Names that contain "nat":
        <ul><xsl:apply-templates select=".//participant[contains(FirstName,'nat')]"/></ul>
        First Names that contain "nat" and "Nat":
        <ul><xsl:apply-templates select=".//participant[contains(translate(FirstName,'N','n'),'nat')]"/></ul>
      </body>
    </html>
  </xsl:template>


  ''First Names that contain "nat":''
<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/></li>
</xsl:template>


  &lt;ul&gt;
</xsl:stylesheet>
</pre>


  &lt;xsl:apply-templates select="''.//participant[contains(FirstName,'nat')''
=== Union of XPaths ===
]"/&gt;
 
  &lt;/ul&gt;
 
  ''First Names that contain "nat" and "Nat":''
 
  &lt;ul&gt;
 
    &lt;xsl:apply-templates select="''.//participant[contains''
 
''                        (translate(FirstName,'N','n'),'nat')]''
"/&gt;
 
    &lt;/ul&gt;
 
  &lt;/body&gt;
 
  &lt;/html&gt;
 
&lt;/xsl:template&gt;
 
��
 
&lt;xsl:template match="participant"&gt;
 
  &lt;li&gt;&lt;xsl:value-of select="FirstName"/&gt;&lt;/li&gt;
 
&lt;/xsl:template&gt;
 
 
 
=== 2.8 Union of XPaths ===


* Union Xpaths combine more than one XPath (and all the resulting nodes are returned).
* Union Xpaths combine more than one XPath (and all the resulting nodes are returned).
Line 842: Line 603:


  &lt;xsl:template match="*|/"&gt;
  &lt;xsl:template match="*|/"&gt;
   &lt;xsl:apply-templates/&gt;
   &lt;xsl:apply-templates/&gt;
  &lt;/xsl:template&gt;
  &lt;/xsl:template&gt;


Line 850: Line 609:


  &lt;xsl:template match="para|description"&gt;
  &lt;xsl:template match="para|description"&gt;
   &lt;p&gt;&lt;xsl:apply-templates/&gt;&lt;/p&gt;
   &lt;p&gt;&lt;xsl:apply-templates/&gt;&lt;/p&gt;
  &lt;/xsl:template&gt;
  &lt;/xsl:template&gt;


=== 2.9 List of commonly used XPath expressions ===
=== 2.9 List of commonly used XPath expressions ===
Line 1,000: Line 755:


|}
|}
== 3. XSLT reminder ==
* In most situations, writing simple XSLT rules will do
* Do not attempt to use looping constructs etc. when you don't have to
* There is no special "magic" for dealing with images, links, stylesheets etc. Simply:
** look at your XML
** figure out how to translate into equivalent HTML (or whatever you are translating into)
==== Example 3-1: Dealing with pictures ====
;XML file with picture file names (file images.xml)
&lt;?xml version="1.0"?&gt;
&lt;?xml-stylesheet href="images.xsl" type="text/xsl"?&gt;
&lt;page&gt;
  &lt;title&gt;Hello Here are my images&lt;/title&gt;
  &lt;list&gt;
    ''&lt;image&gt;''
dolores_001.jpg''&lt;/image&gt;''
    &lt;image&gt;dolores_002.jpg&lt;/image&gt;
    &lt;image&gt;dolores_002.jpg&lt;/image&gt;
    &lt;image2&gt;scrolls.jpg &lt;/image2&gt;
    &lt;image2&gt;scrolls.jpg &lt;/image2&gt;
    ''&lt;image3''
  source="dolores_002.jpg"&gt;Recipe image''&lt;/image3&gt;''
  &lt;/list&gt;
  &lt;comment&gt;Written by DKS.&lt;/comment&gt;
&lt;/page&gt;
��
;XSLT stylesheet (file images.xsl)
&lt;xsl:template match="list"&gt;
    Apply templates for image elements:
    &lt;xsl:apply-templates select="''image''
"/&gt;
    This will only insert the first "image2" element contents it finds:
    &lt;p&gt; &lt;img src="{image2}"/&gt; &lt;/p&gt;
    And another template for a tag image3 element (with an attribute)
    &lt;xsl:apply-templates select="''image3''
"/&gt;
&lt;/xsl:template&gt;
* This rule will insert the content of the image element into the value of src="".
  &lt;xsl:template match="image"&gt;
    &lt;p&gt; &lt;img src="''{.}''
"/&gt; &lt;/p&gt;
  &lt;/xsl:template&gt;
* This rule will insert the value of the source attribute into the value of src and also insert the contents of the the image3 element.
  &lt;xsl:template match="image3"&gt;
    &lt;p&gt; &lt;img src="''{@source}''
"/&gt;''&lt;xsl:value-of select="."/&gt;''
  &lt;/p&gt;
  &lt;/xsl:template&gt;
== 4. Multiple templates for one element ==
* XSLT allows to define multiple rules for the same XPath by using the "mode" attribute
* This construct is frequently used to produce table of contents
;Parts of the XML file (file douglas-recipes.xml)
&lt;list&gt;
  &lt;recipe id="r1"&gt;
    &lt;recipe_name&gt;TACOS&lt;/recipe_name&gt;
    &lt;meal&gt;Dinner&lt;/meal&gt;
    &lt;ingredients&gt;
      &lt;item&gt;3 taco shells&lt;/item&gt;
      &lt;item&gt;1 pkg hamburger 100g&lt;/item&gt;
      ........
    &lt;/ingredients&gt;
��
    &lt;directions&gt;
      &lt;bullet&gt;Oven on at 180 degrees.&lt;/bullet&gt;
      ......
      &lt;bullet&gt;Cut up lettuce.&lt;/bullet&gt;
    &lt;/directions&gt;
  &lt;/recipe&gt;
��
  &lt;recipe id="r2"&gt;
  ....
&lt;/list&gt;
;XSLT fragment (file douglas-recipes.xsl)
&lt;xsl:template match="list"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
    &lt;head&gt; &lt;title&gt;Recipes&lt;/title&gt; &lt;/head&gt;
    &lt;body bgcolor="#ffffff"&gt;
    &lt;h1&gt;Recipes&lt;/h1&gt;
    &lt;h2&gt;Contents&lt;/h2&gt;
    &lt;p&gt; &lt;xsl:apply-templates ''select="recipe" mode="toc"/''
&gt; &lt;/p&gt;
    &lt;xsl:apply-templates select="''recipe''
"/&gt;
    &lt;/body&gt; &lt;/html&gt;
&lt;/xsl:template&gt;
* We define 2 rules for "recipe": One will have a mode="toc"
* The next rule will create the table of contents.
** It will use the recipe_name as link
** It will use the id attribute to create an internal href link
&lt;xsl:template ''match="recipe" mode="toc"''
&gt;
  &lt;p&gt;&lt;a ''href="#{@id}''
"&gt;&lt;xsl:value-of select="''recipe_name''
"/&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/xsl:template&gt;
* This rule is almost "normal", except that we insert a name anchor
&lt;xsl:template ''match="recipe"''
&gt;
  &lt;h1&gt;&lt;a ''name="{@id}''
"&gt;&lt;xsl:value-of select="recipe_name"/&gt;&lt;/a&gt; &lt;/h1&gt;
  &lt;xsl:apply-templates select="meal"/&gt;
  &lt;xsl:apply-templates select="ingredients"/&gt;
  &lt;xsl:apply-templates select="directions"/&gt; &lt;/xsl:template&gt;
;HTML result
&lt;?xml version="1.0" encoding="iso-8859-1"?&gt;
��
&lt;!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
    &lt;head&gt;
      &lt;title&gt;Recipes&lt;/title&gt;
    &lt;/head&gt;
    &lt;body bgcolor="#ffffff"&gt;
      &lt;h1&gt;Recipes&lt;/h1&gt;
      &lt;h2&gt;Contents&lt;/h2&gt;
      &lt;p&gt;
          &lt;p&gt; ''&lt;a href="#r1"&gt;TACOS&lt;/a&gt; ''
&lt;/p&gt;
          &lt;p&gt; ''&lt;a href="#r2"&gt;VOL AU VENT (one person)&lt;/a&gt; ''
&lt;/p&gt;
      &lt;/p&gt;
      &lt;hr/&gt;
      &lt;h1&gt;
        '' &lt;a name="r1"&gt;TACOS&lt;/a&gt;''
      &lt;/h1&gt;
      &lt;p&gt; Type: Dinner&lt;/p&gt;
== 5. Conditional XSLT and whitespaces ==
* Although many conditionals can be expressed with XPath and according selection rules, XSLT provides 2 typical programming constructs to handle "if" and "if-then-else" situations.
* When you use XPath functions like position(), you have to be very careful about whitespaces
=== 5.1 Simple if ===
==== Syntax for xsl:if: ====
&lt;xsl:if test = "boolean_expression"&gt;
&lt;!-- Content or xsl instructions here --&gt;
&lt;/xsl:if&gt;
==== Example 5-1: Display lists, the last element differently with xsl:if ====
* Warning: This only works in standards compliant browsers if you either eliminate whitespaces from your XML file or if you add the following XSL instruction at the beginning:
&lt;xsl:strip-space elements="element_name element_name ...."/&gt;
&lt;xsl:strip-space elements="ingredients"/&gt;
;XML (file ingredient-list.xml)
&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt;
&lt;?xml-stylesheet href="ingredient-list.xsl" type="text/xsl"?&gt;
&lt;ingredients&gt;
  &lt;item&gt;3 taco shells&lt;/item&gt;
  &lt;item&gt;1 pkg hamburger 100g&lt;/item&gt;
  &lt;item&gt;Taco mix&lt;/item&gt;&lt;item&gt;Lettuce&lt;/item&gt;&lt;/ingredients&gt;
;XSL (file ingredient-list.xsl)
  &lt;xsl:template match="/ingredients"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
    &lt;head&gt; &lt;title&gt;Ingrediant list&lt;/title&gt; &lt;/head&gt;
    &lt;body bgcolor="#ffffff"&gt;
      Here is a list of recipe ingrediants:
    &lt;p&gt; &lt;xsl:apply-templates select="item"/&gt;. &lt;/p&gt;
      Here is a list of recipe ingrediants, this time numbered:
    &lt;p&gt; &lt;xsl:apply-templates select="item" mode="numb"/&gt;. &lt;/p&gt;
    &lt;/body&gt;
  &lt;/html&gt;
&lt;/xsl:template&gt;
��
&lt;xsl:template match="item"&gt;
  &lt;xsl:value-of select="."/&gt;
  &lt;xsl:if ''test="position()!=last()"''
&gt; &lt;xsl:text&gt;, &lt;/xsl:text&gt; &lt;/xsl:if&gt;
&lt;/xsl:template&gt;
��
&lt;xsl:template match="item" mode="numb"&gt;
  (&lt;xsl:value-of select="''position()''
"/&gt;)
  &lt;xsl:value-of select="."/&gt;
  &lt;xsl:if ''test="position()!=last()"''
&gt; &lt;xsl:text&gt;, &lt;/xsl:text&gt; &lt;/xsl:if&gt;
&lt;/xsl:template&gt;
��
&lt;/xsl:stylesheet&gt;
;HTML results
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
    &lt;head&gt;
      &lt;title&gt;Ingrediant list&lt;/title&gt;
    &lt;/head&gt;
    &lt;body bgcolor="#ffffff"&gt;
      Here is a list of recipe ingrediants:
    &lt;p&gt;3 taco shells'',''
  1 pkg hamburger 100g'',''
  Taco mix'',''
  Lettuce''.''
  &lt;/p&gt;
      Here is a list of recipe ingrediants, this time numbered:
    &lt;p&gt;
  ''(1)''
  3 taco shells'',''
  ''(2) ''
1 pkg hamburger 100g,
  (3) Taco mix,
  (4) Lettuce. &lt;/p&gt;
    &lt;/body&gt;
&lt;/html&gt;
;Same logic would apply e.g. to building references
&lt;xsl:template match="reference"&gt;
  &lt;xsl:apply-templates
        select="author|ref|title|edition|publisher|pubPlace|publicationYear"/&gt;.
  &lt;/xsl:template&gt;
  ��
  &lt;xsl:template match="author|edition|publisher|pubPlace|publicationYear"&gt;
  &lt;xsl:apply-templates/&gt;
  &lt;xsl:if test="position() !=last()"&gt;, &lt;/xsl:if&gt;
  &lt;/xsl:template&gt;
=== 5.2 If-then-else ===
==== Syntax: ====
&lt;xsl:choose&gt;
&lt;!-- Content: (xsl:when , xsl:otherwise?) --&gt;
&lt;/xsl:choose&gt;
&lt;xsl:when test = "boolean-expression"&gt;
&lt;!-- Content: template --&gt;
&lt;/xsl:when&gt;
&lt;xsl:otherwise&gt;
&lt;!-- Content: template --&gt;
&lt;/xsl:otherwise&gt;
==== Example 5-2: Animal colors with xsl:choose ====
;XML (file animals.xml)
&lt;example&gt;
  &lt;title&gt;Animals with colors&lt;/title&gt;
  &lt;list&gt;
  &lt;animal color="black"&gt;Panther&lt;/animal&gt;
  &lt;animal color="complicated with spots"&gt;Panther&lt;/animal&gt;
  &lt;animal color="white"&gt;Polar bear&lt;/animal&gt;
  &lt;animal color="green"&gt;Frog&lt;/animal&gt;
  &lt;animal&gt;Cow&lt;/animal&gt;
  &lt;/list&gt;
&lt;/example&gt;
;XSLT template for animal (file animals:xsl)
&lt;xsl:template match="animal"&gt;
&lt;li&gt;
  &lt;xsl:choose&gt;
    &lt;xsl:when ''test="@color='black'"''
&gt;
      &lt;p style="color:black;font-weight:bold;"&gt; &lt;xsl:value-of select="."/&gt; &lt;/p&gt;
    &lt;/xsl:when&gt;
��
    &lt;xsl:when ''test="@color='green'"''
&gt;
      &lt;p style="color:green;font-weight:bold;"&gt; &lt;xsl:value-of select="."/&gt; &lt;/p&gt;
    &lt;/xsl:when&gt;
��
    &lt;xsl:''otherwise''
&gt;
      &lt;p style="color:cyan"&gt; &lt;xsl:value-of select="."/&gt; &lt;/p&gt;
    &lt;/xsl:otherwise&gt;
  &lt;/xsl:choose&gt;
&lt;/li&gt;
&lt;/xsl:template&gt;
;HTML (some)
&lt;li&gt;&lt;p style="color:black;font-weight:bold;"&gt;Panther&lt;/p&gt; &lt;/li&gt;
&lt;li&gt;&lt;p style="color:cyan"&gt;Panther&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p style="color:cyan"&gt;Polar bear&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p style="color:green;font-weight:bold;"&gt;Frog&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p style="color:cyan"&gt;Cow&lt;/p&gt;&lt;/li&gt;
== 6. Looping ==
* Most of the time you do "looping" with templates (as in all previous examples)
* There is a xsl:for-each looping construct. It is useful to write more compact code, to use it with sorting and functional programming constructs (not explained here).
'' xsl:for-each select="XPath" ''
==== Example 6-1: Translating database query output into an HTML table ====
;XML (file rowset.xml)
* Typical database query output may look like this
* E.g. survey data will present as a series of rows of the same length
* We would like to translate each ROW into a table row and each child as a table cell
��
&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt;
&lt;?xml-stylesheet href="rowset.xsl" type="text/xsl"?&gt;
&lt;page&gt;
  &lt;ROWSET&gt;
    &lt;ROW&gt;&lt;id&gt;1&lt;/id&gt;&lt;login&gt;test&lt;/login&gt;&lt;fullname&gt;Joe Test &lt;/fullname&gt;
    &lt;food&gt;3&lt;/food&gt;&lt;work&gt;4&lt;/work&gt;&lt;love&gt;5&lt;/love&gt;&lt;leisure&gt;2&lt;/leisure&gt;&lt;/ROW&gt;
    &lt;ROW&gt;&lt;id&gt;2&lt;/id&gt;&lt;login&gt;test2&lt;/login&gt;&lt;fullname&gt;Janine Test &lt;/fullname&gt;
    &lt;food&gt;3&lt;/food&gt;&lt;work&gt;4&lt;/work&gt;&lt;love&gt;6&lt;/love&gt;&lt;leisure&gt;2&lt;/leisure&gt;&lt;/ROW&gt;
  .......
  &lt;/ROWSET&gt;
&lt;/page&gt;
;XSLT (file rowset.xsl)
&lt;xsl:template match="ROWSET"&gt;
    &lt;table border="2" cellspacing="1" cellpadding="6"&gt;
    &lt;tr&gt;&lt;th&gt;id&lt;/th&gt;
        &lt;th&gt;Login&lt;/th&gt;
        &lt;th&gt;Full Name&lt;/th&gt;
        &lt;th&gt;food&lt;/th&gt;&lt;th&gt;work&lt;/th&gt;&lt;th&gt;love&lt;/th&gt;&lt;th&gt;leisure&lt;/th&gt;
      &lt;/tr&gt;
      ''&lt;xsl:for-each select="ROW"&gt;''
      &lt;tr&gt;
      &lt;td&gt;&lt;xsl:value-of select="id"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="login"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="fullname"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="food"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="work"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="love"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="leisure"/&gt;&lt;/td&gt;
      &lt;/tr&gt;
      ''&lt;/xsl:for-each&gt;''
    &lt;/table&gt;
&lt;/xsl:template&gt;
=== 6.1 Looping with a sort ===
* xsl:sort can sort a list according to several criteria, can be used more than once
&lt;xsl:sort
  ''select = "Xpath"''
  data-type = { "text" | "number" }
  order = { "ascending" | "descending" }
  case-order = { "upper-first" | "lower-first" } /&gt;
==== Example 6-2: Sort a participants list according to qualification ====
;XML fragment (file: participants.xml)
&lt;?xml version="1.0"?&gt;
&lt;?xml-stylesheet href="participants.xsl" type="text/xsl"?&gt;
  &lt;participants&gt;
  &lt;participant&gt;
    &lt;FirstName&gt;Daniel&lt;/FirstName&gt;
    &lt;qualification&gt;8&lt;/qualification&gt;
    &lt;description&gt;Daniel will be the tutor&lt;/description&gt;
    &lt;FoodPref picture="dolores_001.jpg"&gt;Sea Food&lt;/FoodPref&gt;
  &lt;/participant&gt;
  &lt;participant&gt;
    &lt;FirstName&gt;Jonathan&lt;/FirstName&gt;
    &lt;qualification&gt;5&lt;/qualification&gt;
    &lt;FoodPref picture="dolores_002.jpg"&gt;Asian&lt;/FoodPref&gt;
  ......
  &lt;/participant&gt;
;Part of XSLT (file: participants.xsl)
��
&lt;xsl:template match="participants"&gt;
    &lt;table border="2" cellspacing="1" cellpadding="6"&gt;
    &lt;tr&gt;&lt;th&gt;Qualification&lt;/th&gt;
        &lt;th&gt;First Name&lt;/th&gt;
        &lt;th&gt;Description&lt;/th&gt;
        &lt;th&gt;Food Picture&lt;/th&gt;
      &lt;/tr&gt;
      &lt;xsl:for-each ''select="participant"''
&gt;
        ''&lt;xsl:sort''
  ''select="qualification"''
/&gt;
      &lt;tr&gt;
      &lt;td&gt;&lt;xsl:value-of select="qualification"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="FirstName"/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select="description"/&gt;&lt;/td&gt;
        &lt;td&gt;&lt;xsl:if test="FoodPref/@picture"&gt;
            &lt;img src="{FoodPref/@picture}"/&gt;&lt;/xsl:if&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;/xsl:for-each&gt;
    &lt;/table&gt;
&lt;/xsl:template&gt;
== 7. Moving on ==
* XSLT is a full programming language, but further XSLT constructs are out of scope for this class......
* Just for your information, I present a small example that demonstrates function calls.
==== Example 7-1: Display ingredients with increasing fonts ====
;XML (file: ingredient-list2.xml)
&lt;ingredients&gt;  &lt;item&gt;3 taco shells&lt;/item&gt;&lt;item&gt;1 pkg hamburger 100g&lt;/item&gt;
  &lt;item&gt;Taco mix&lt;/item&gt; &lt;item&gt;50 g of cheese&lt;/item&gt;  &lt;item&gt;1 tomato&lt;/item&gt;
  &lt;item&gt;1 carot&lt;/item&gt; &lt;item&gt;Lettuce&lt;/item&gt;&lt;/ingredients&gt;
;XSLT (file ingredient-list2.xsl)
&lt;xsl:template match="/ingredients"&gt;
  &lt;html&gt;
  &lt;head&gt; &lt;title&gt;Ingrediant list&lt;/title&gt; &lt;/head&gt;
    &lt;body bgcolor="#ffffff"&gt;
      Here is a list of recipe ingrediants:
      &lt;xsl:for-each select="item"&gt;
        &lt;xsl:''call-template''
  name="''display_item''
"&gt;
          &lt;xsl:''with-param''
  name="''position''
" select="position()"/&gt;
        &lt;/xsl:call-template&gt;
      &lt;/xsl:for-each&gt;
    &lt;/body&gt;
  &lt;/html&gt;
&lt;/xsl:template&gt;
&lt;!-- you can change the value of these 2 parameters --&gt;
  &lt;''xsl:param''
  name="''initial_size''
" select="5"/&gt;
  &lt;''xsl:param''
  name="''multiplier''
" select="3"/&gt;
  ��
&lt;xsl:''template name''<nowiki>
="</nowiki>''display_item''
"&gt;
  &lt;xsl:''param''
  name="''position''
"/&gt;
  &lt;xsl:''variable''
  name="font_size"
                select="$initial_size  $position * $multiplier"/&gt;
  &lt;xsl:''variable''
  name="color"&gt;
    &lt;xsl:choose&gt;
      &lt;xsl:when test="$position mod 3 = 0"&gt;
            &lt;xsl:text&gt;yellow&lt;/xsl:text&gt;&lt;/xsl:when&gt;
      &lt;xsl:when test="$position mod 3 = 1"&gt;
            &lt;xsl:text&gt;red&lt;/xsl:text&gt;  &lt;/xsl:when&gt;
      &lt;xsl:when test="$position mod 3 = 2"&gt;
            &lt;xsl:text&gt;blue&lt;/xsl:text&gt;  &lt;/xsl:when&gt;
      &lt;xsl:otherwise&gt;&lt;xsl:text&gt;green&lt;/xsl:text&gt;&lt;/xsl:otherwise&gt;
    &lt;/xsl:choose&gt;
  &lt;/xsl:''variable''
&gt;
  &lt;p style="color:{$color}; font-size: {$font_size}pt;"&gt;
      &lt;xsl:value-of select="."/&gt;&lt;br /&gt;
  [Pos = &lt;xsl:value-of select="$position"/&gt;,
    Multip. = &lt;xsl:value-of select="$multiplier"/&gt;,
    Font size = &lt;xsl:value-of select="$font_size"/&gt;] &lt;/p&gt;
&lt;/xsl:template&gt;
��
== 8. Next steps ==
=== 8.1 Reading ===
Carey (pp. 297-317, 317-335)
Optional: 1 or 2 case problems
=== 8.2 Next modules ===
;Module 7
* XML Schema
== 9. Homework: mini-project 6 ==
Due: Monday Feb. 19 16:00h
=== 9.1 Task ===
;Create an XSLT transformation to (X)HTML.
* Create a DTD and a valid XML example file
* Translate the XML document to somewhat valid HTML or XHTML
* Write some user documentation (i.e. make sure others could use your DTD and stylesheet)
* Make use of some more advanced XPath and XSLT constructs (but be '' reasonable'' !!!)
* Take into account critique for homework 5
* You may reuse materials from previous homework
** I strongly suggest to base this project on homework 5 (XSLT)
=== 9.2 Approximate evaluation grid ===
;Minimal requirement:
{| border="1"
! rowspan="1" colspan="1" |
Features
! rowspan="1" colspan="1" |
Expect a
|-
| rowspan="1" colspan="1" |
Valid XML (DTD) and well-formed XSLT style sheet that does a translation
| rowspan="1" colspan="1" |
D
|-
| rowspan="1" colspan="1" |
An XML contents that displays as (X)HTML in a web browser of your choice
| rowspan="1" colspan="1" |
C
|}
;You will get extra points for
{| border="1"
! rowspan="1" colspan="1" |
Extra features
! rowspan="1" colspan="1" |
Extra points ( /- quality)
|-
| rowspan="1" colspan="1" |
Inserted comments &lt;!-- ... --&gt; in the various files (XML, XSLT or CSS)
| rowspan="1" colspan="1" |
|-
| rowspan="1" colspan="1" |
XML data organization that is appropriate for your domain
| rowspan="1" colspan="1" |
|-
| rowspan="1" colspan="1" |
Complexity of style sheet (kinds of transformations)
| rowspan="1" colspan="1" |
...
|-
| rowspan="1" colspan="1" |
Ergonomic and nice presentation (style and function)
| rowspan="1" colspan="1" |
...
|-
| rowspan="1" colspan="1" |
Your result document is valid HTML or XHTML
| rowspan="1" colspan="1" |
|-
| rowspan="1" colspan="1" |
A 1-2 page '' user manual'' that explains a user how to use your DTD and stylesheet
| rowspan="1" colspan="1" |
...
|-
| rowspan="1" colspan="1" |
A 1 page report that discusses your implementation
| rowspan="1" colspan="1" |
...
|}
* To get a B: Produce a useful (X)HTML document from valid XML
* To get an A:
** Create a useful DTD, an ergonomic XSLT, a useful manual and a report
** Alternatively: Create a really difficult XSLT and a good report
;Submission format
I require a double submission:
# Paper copies to be turned in a start of Monday lesson
# Electronic copies to be uploaded to the server in folder homework/project_6 !!!<br /> Please make sure to name these documents according to the following rules:
your_name.xml or your_name.html or your_name.xhtml (mandatory)
your_name.dtd (optional)
your_name.{doc|pdf|html} Chose the format you like (optional)


== links ==
== links ==

Revision as of 16:52, 25 November 2007

This article or section is currently under construction

In principle, someone is working on it and there should be a better version in a not so distant future.
If you want to modify this page, please discuss it with the person working on it (see the "history")

<pageby nominor="false" comments="false"/>

Introduction

Prerequisites

  • Editing XML (being able to use a simple DTD)
  • Introductory XSLT (xsl:template, xsl:apply-templates and xsl:value-of)
  • Know about the role of XPath with respect to XSLT

Objectives

  • Better understand XPath expressions
  • Learn some XSLT programming constructions (conditions and loops)
  • Being able to cope with most XML to HTML transformations

Disclaimer

  • There may be typos (sorry) and mistakes (sorry again)
  • Please also consult a textbook !

Introduction to XML Path Language

Definition and history

  • XPath is a language for addressing parts of an XML document
  • In support of this primary purpose, it also provides basic facilities for manipulation of strings, numbers and booleans.
  • XPath uses a compact non-XML syntax (to facilitate use of XPath within URIs and XML attribute values).
  • XPath gets its name from its use of a path notation as in URLs for navigating through the hierarchical structure of an XML document.
  • XPath was defined at the same time as XSLT (nov 1999)
  • Initally, it was developped to support XSLT and XPointer (XML Pointer Language used for XLink, XInclude, etc.)
Specifications

XSLT, XQuery and XPath

  • Each time a given XSLT or XQuery instruction needs to address (refer to) parts of an XML document we use XPath expressions.
  • XPath expressions also can contain functions, simple math and boolean expressions

With XSLT, XPath expressions are typicially used in match , select and test attributes:

Xpath expressions in an XSLT template

The XPath Syntax and the document model

Xpath Syntax

XPath expressions (at least the simple ones) look a bit like file paths. E.g.

/section/title

means: find all title nodes below section nodes

Primary (relatively simple) XPath expressions

Xml-xpath-3.png

Result of an Xpath
  • Can be various things, e.g. sets of nodes, a single node, a number, etc
  • Most often the result is a set of nodes
There are two notations for location paths
  1. abbreviated (less available options)
    • e.g. para is identical to child::para
  2. unabbreviated (not presented in these slides !!)
    • e.g. " child::para " would define the para element children of the current context node.
The formal specification of an XML Path
  • is very complex, i.e. has about 39 clauses and is very difficult to understand
  • Some expressions shown here are beyound the scope of this tutorial, don't panic !

2.2 The document model of XPath

  • XPath sees an XML document as a tree structure
  • Each information (XML elements, attributes, text, etc.) is called a node. This is fairly similar to the W3C DOM model an XML or XSLT processor would use.
Nodes that XPath can see
  • root node
    • ATTENTION: The root is not necessarily the XML root element. E.g. processing instructions like a stylesheet declaration are also nodes.
  • Elements and attributes
  • Special nodes like comments, processing instructions, namespace declarations.
Nodes XPath can't see
  • XPath looks at the final document, therefore it can't see entities and document type declarations....
The XML context
  • What a given XPath expression means, is always defined by a given XML context, i.e. the current node in the XML tree

2.3 Element Location Paths

We present a few expressions for locating nodes. This is not complete and we will use abbreviated syntax.

Document root node
returns the document root (which is not necessarily the XML root!)

/

Direct child element

XML_element_name

Direct child of the root node

/XML_element_name

Child of a child

XML_element_name/XML_element_name

Descendant of the root

//XML_element_name

Descendant of a node

XML_element_name//XML_element_name

Parent of a node

../

A far cousin of a node

../../XML_element_name/XML_element_name/XML_element_name

Example Extracting titles from an XML file with XSLT

An XML document (file
xpath-jungle.xml used throughout the rest)

<?xml version="1.0"?>
<project>
 <title>The Xpath project</title>
 <participants>
  <participant>
    <FirstName>Daniel</FirstName>
    <qualification>8</qualification>
    <description>Daniel will be the tutor</description>
    <FoodPref picture="dolores_001.jpg">Sea Food</FoodPref>
  </participant>
  <participant>
    <FirstName>Jonathan</FirstName>
    <qualification>5</qualification>
    <FoodPref picture="dolores_002.jpg">Asian</FoodPref>
  </participant>
  <participant>
   <FirstName>Bernadette</FirstName>
   <qualification>8</qualification>
    <description>Bernadette is an arts major</description>
  </participant>
  <participant>
   <FirstName>Nathalie</FirstName>
   <qualification>2</qualification>
  </participant>
 </participants>
 <problems>
  <problem>
    <title>Initial problem</title>
    <description>We have to learn something about Location Path</description>
    <difficulty level="5">This problem should not be too hard</difficulty>
  </problem>
  <solutions>
   <item val="low">Buy a XSLT book</item>
   <item val="low">Find an XSLT website</item>
   <item val="high">Register for a XSLT course and do exercices</item>
  </solutions>
   <problem>
    <title>Next problem</title>
    <description>We have to learn something about predicates</description>
    <difficulty level="6">This problem is a bit more difficult</difficulty>
  </problem>
  <solutions>
   <item val="low">Buy a XSLT book</item>
   <item val="medium">Read the specification and do some exercises</item>
   <item val="high">Register for a XPath course and do exercices</item>
  </solutions>
 </problems>
</project>
Task

We would like to get a simple list of problem titles

Solution

XSLT template (file: xpath-jungle-1.xsl)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/project">
    <html>
      <body bgcolor="#FFFFFF">
        <h1><xsl:value-of select="title" /></h1>
        Here are the titles of our problems: <ul>
        <xsl:apply-templates select="problems/problem" /> 
      </ul>
      </body>
    </html>
  </xsl:template>

<xsl:template match="problems/problem">
  <li><xsl:value-of select="title" /></li>
</xsl:template>

</xsl:stylesheet>
(1) XSLT template for the root element
  • The XPath of the "match" means: applies to project element node, descendant of root node
  • Execution context of this template is therefore the element "project "
  • xsl:apply-templates will select a rule for descendant " problem ".
(2) XSLT template for the problem element
  • The second rule will be triggered by the first rule, because problems/problem is indeed a descendant of the project element
(3) Result HTML
<html>
   <body bgcolor="#FFFFFF">
      <h1>The Xpath project</h1>
      Here are the titles of our problems:
      <ul>
         <li>Initial problem</li>
         <li>Next problem</li>
      </ul>
   </body>
</html>

Attribute Location Paths

Top find an attribute of a child element of the current context

@attribute_name

Example:

@val
Find attributes of an element in a longer location path starting from root

/element_name/element_name/@attribute_name

Example:

/project/problems/solutions/item/@val
Find attributes in the whole document

//@attribute_name

Example 2-2: Make an html img link from an attribute

XML fragment

Same as above

Task

Display a list of First Names plus their food preferences

XSLT (File xpath-jungle-2.xsl)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>What do we know about our participants ?</h1>
        Here are some food preferences: <ul>
        <xsl:apply-templates select=".//participant" /> 
      </ul>
      </body>
    </html>
  </xsl:template>

<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/>
  <xsl:apply-templates select="FoodPref"/>
  </li>
</xsl:template>

<xsl:template match="FoodPref">
  prefers <xsl:value-of select="."/>. 
  <img src="{@picture}"/> <br clear="all"/>
</xsl:template>

</xsl:stylesheet>

  • The second rule will display names of participants and launch a template for FoodPref
  • Note: Not all participants have a FoodPref element. If it is absent it will just be ignored.
  • The third rule (FoodPref) displays the text (contents) of FoodPref and then makes an HTML img tag


Parts of the result
  <h1>What do we know about our participants ?</h1>
      Here are some food preferences:
      <ul>
         <li>Daniel prefers Sea Food.
            <img src="dolores_001.jpg"><br clear="all"></li>
         <li>Jonathan
            prefers Asian.
            <img src="dolores_002.jpg"><br clear="all"></li>
         <li>Bernadette</li>
         <li>Nathalie</li>
      </ul>

Location wildcards

  • Sometimes (but not often!), it is useful to work with wildcards
  • You have to understand that only one rule will be applied/element. Rules with wildcards have less priority and this is why "your rules" are applied before the system defaults.
Find all child nodes of type XML element

*

Find all child nodes (including comments, etc.)

node()

Find all element attributes

@*

Find all text nodes

text()

FYI
The system built-in (default) rules rely on wildcards

This rule applies to the document root and all other elementsn

<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>

Text and attribute values are just copied (see

<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>

XPaths with predicates

  • A predicate is an expression that can be true or false
  • It is appended within [...] to a given location path and will refine results
  • More than one predicate can be appended to and within (!) a location path
  • Expressions can contain mathematical or boolean operators
Find element number N in a list

XML_element_name [ N ]

/project/participants/participant[2]
/project/participants/participant[2]/FirstName
Find elements that have a given attribute

XML_element_name [ @attribute_name ]

Find elements that have a given element as child

XML_element_name [ XML_element_name ]//participant[FoodPref]

Mathematical expressions
  • Use the standard operators, except div instead of / ")
- * div mod
  • mod is interesting if you want to display a long list in table format
5 mod 2 returns 1, "7 mod 2" and "3 mod 2" too
Boolean operators (comparison, and, or)
  • List of operators (according to precedence)
<=, <, >=, >
=, !=
and, or


Examples
  • Return all exercise titles with a grade bigger than 5.

//exercise[note>5]/title

  • Find elements that have a given attribute with a given value

XML_element_name [ @attribute_name = 'value']

//solutions/item[@val="low"]
  • Example XSLT template that will match all item elements with val="low".
<xsl:template match=" //item[@val='low'] ">
   <xsl:value-of select="." />
</xsl:template>
Note
Usually expressions also contain functions
  • Return last five elements of a list
author [(last() - 4) <= position()) and (position() <= last())]
  • Return all Participant nodes with a contents of FirstName bigger than 7 characters:
"//Participant[string-length(FirstName)>=8]"

Example 2-3: Retrieve selected elements

The XSLT stylesheet (file xpath-jungle-3.xsl)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>What do we know about our participants ?</h1>
        Here are some food preferences: <ul>
        <xsl:apply-templates select=".//participant" /> 
      </ul>
      </body>
    </html>
  </xsl:template>

<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/>
  <xsl:apply-templates select="FoodPref"/>
  </li>
</xsl:template>

<xsl:template match="FoodPref">
  prefers <xsl:value-of select="."/>. 
  <img src="{@picture}"/> <br clear="all"/>
</xsl:template>

</xsl:stylesheet>
HTML result
<html>
   <body bgcolor="#FFFFFF">
      <h1>Retrieve selected elements</h1>
      Here is the name of participant two:
      <ul>
         <li>Jonathan</li>
      </ul>
      Here are all participant's firstnames that have a food preference:
      <ul>
         <li>Daniel</li>
         <li>Jonathan</li>
      </ul>
      Here are all items that have a value of "high"
      <ul>
         <li>Register for a XSLT course and do exercices</li>
         <li>Register for a XPath course and do exercices</li>
      </ul>
   </body>
</html>

XPath functions

  • XPath defines a certain number of functions
    • You can recognize a function because it has "()".
  • Functions are programming constructs that will return various kinds of informations, e.g.
    • true / false
    • a number
    • a string
    • a list of nodes
  • It is not obvious to understand these ....
  • There are restrictions on how you can use functions (stick to examples or the reference)
last()

last() gives the number or nodes within a context

position()

position() returns the position of an element with respect to other children for a parent

count(node-set)

count gives the number of nodes in a node set (usually found with an XPath).

starts-with(string, string)

returns TRUE if the second string is part of the first and starts off the first

//Participant[starts-with(Firstname,'Berna')]"
contains(string, string)

returns TRUE if the second string is part of the first

//Participant[contains(FirstName,'nat')]
string-length(string)

returns the length of a string

number(string)

transforms a string into a number

sum(node-set)

computes the sum of a given set of nodes.
If necessary, does string conversion with number()

round(number)

round a number, e.g. 1.4 becomes 1 and 1.7 becomes 2

translate(string1, string2, string3)

translates string1 by substituting string2 elements with string3 elements

Example 2-4: Computation of an average

  • We would like to compute the average of participant's qualifications
<participant><FirstName>Daniel</FirstName>
             <qualification>8</qualification>
   </participant>
The XSLT stylesheet (file xpath-jungle-4.xsl)
  • We compute the sum of a node-set and then divide by the number of nodes
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>Qualification level of participants</h1>
        Average is
        <xsl:value-of select="sum(.//participant/qualification) div count(.//participant/qualification)"/>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
HTML result
<html>
   <body bgcolor="#FFFFFF">
      <h1>Qualification level of participants</h1>
      Average is
      5.75
   </body>
</html>

Example 2-5: Find first names containing 'nat'

The XSLT stylesheet (file xpath-jungle-5.xsl)
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
      <body bgcolor="#FFFFFF">
        <h1>Do we have a "nat" ?</h1>
        First Names that contain "nat":
        <ul><xsl:apply-templates select=".//participant[contains(FirstName,'nat')]"/></ul>
        First Names that contain "nat" and "Nat":
        <ul><xsl:apply-templates select=".//participant[contains(translate(FirstName,'N','n'),'nat')]"/></ul>
      </body>
    </html>
  </xsl:template>

<xsl:template match="participant">
  <li><xsl:value-of select="FirstName"/></li>
</xsl:template>

</xsl:stylesheet>

Union of XPaths

  • Union Xpaths combine more than one XPath (and all the resulting nodes are returned).
  • A typical example is the default rule which means that the template matches either the root element (i.e. "/" or just any element),
<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>
  • Often this is used to simplify apply-templates or even templates themselves. E.g. the following rules applies to both "description" and "para" elements.
<xsl:template match="para|description">
  <p><xsl:apply-templates/></p>
</xsl:template>

2.9 List of commonly used XPath expressions

Syntax
element

(Type of path)

Example path

Example matches

name

child element name

project

<project> ...... </project>

/

child / child

project/title

<project> <title> ... </title>

/

(root element)

//

descendant

project//title

<project><problem> <title>....</title>

//title

<root>... <title>..</title> (any place)

*

"wildcard"

*/title

<bla> <title>..</title> and <bli> <title>...</title>

|

"or operator

title|head

<title>...</title> or <head> ...</head>

*|/|@*

All elements: root, children and attributes

.

current element

.

../

parent element

../problem

<project>

@attr

attribute name

@id

<xyz id="test">...</xyz>

element/@attr

attribute of child

project/@id

<project id="test" ...> ... </project>

@attr='value'

value of attribute

list[@type='ol']

<list type="ol"> ...... </list>

position()

position of element
in parent

position()

last()

number of elements within a context

last()

position()!=last()

links

Introductory tutorials

Other