XPATH_2004_JavaUserGroup
XPATH_2004_JavaUserGroup
http://www.w3.org/TR/xpath
By Michael Dockery
[email protected]
What is XPath?
XPath is a cross-platform language for addressing parts of an XML document!
If the path starts with two slashes ( // ) then all elements in the document that fulfill the
criteria will be selected (even if they are at different levels in the XML tree)!
The following XPath expression selects all the cd elements in the document:
//cd
XPath Expressions
This selects the ROOT element catalog:
/catalog
This selects all the price elements of all the cd elements of the catalog element:
/catalog/cd/price
This selects all the cd elements that have a price element with a value larger than 10.80:
/catalog/cd[price>10.80]
XPath Expressions
Wildcards ( * ) can be used to select unknown XML elements.
This selects all the child elements of all the cd elements of the catalog element:
/catalog/cd/*
This selects all the price elements that are grandchild elements of the catalog element:
/catalog/*/price
This selects the last cd child element of the catalog element (Note: There is no function named first()):
/catalog/cd[last()]
This selects all the cd elements of the catalog element that have a price element:
/catalog/cd[price]
This selects all the cd elements of the catalog element that have a price element with a value of 10.90:
/catalog/cd[price=10.90]
This selects all the price elements of all the cd elements of the catalog element that have a price element
with a value of 10.90:
/catalog/cd[price=10.90]/price
XPath Syntax...
In XPath all attributes are specified by the @ prefix.
This XPath expression selects all cd elements which have an attribute named country:
//cd[@country]
This XPath expression selects all cd elements which have any attribute:
//cd[@*]
This XPath expression selects all cd elements which have an attribute named country with a value of 'UK':
//cd[@country='UK']
XPath Examples
<Basket>
<Cherry flavor=‘sweet’/>
<Cherry flavor=‘bitter’/>
<Cherry/>
<Apple color=‘red’/>
<Apple color=‘red’/>
<Apple color=‘green’/>
…
</Basket>
//Basket/Cherry[@flavor]
XPath Functions
String Functions
concat() Returns the concatenation of all its arguments. string=concat(val1, val2, ..)
contains() Returns true if the second string is contained within the first string, otherwise it returns false.
bool=contains(val,substr)
starts-with() Returns true if the first string starts with the second string, otherwise it returns false.
bool=starts-with(string,substr)
translate() Performs a character by character replacement. It looks in the value argument for characters
contained in string1, and replaces each character for the one in the same position in the string2.
string=translate(value,string1,string2)
XPath Functions
String Functions (Examples)
concat('The',' ','XML') Result: 'The XML'
contains('XML','X') Result: true
normalize-space(' The XML ') Result: 'The XML'
sum() Returns the total value of a set of numeric values in a node-set number=sum(nodeset)
Example: sum(/cd/price)
ceiling() Returns the smallest integer that is not less than the number argument number=ceiling(number)
Example: ceiling(3.14) Result: 4
floor() Returns the largest integer that is not greater than the number argument number=floor(number)
Example: floor(3.14) Result: 3
XPath Functions
Boolean Functions
boolean() Converts the value argument to Boolean and returns true or false bool=boolean(value)
false() Returns false false()
Example: number(false()) Result: 0
true() Returns true true()
Example: number(true()) Result: 1
not() Returns true if the condition argument is false, and false if the condition argument is true bool=not(condition)
Example: not(false())
lang() Returns true if the language argument matches the language of the the xsl:lang element, otherwise it returns
false bool=lang(language)
<?xml version="1.0"?>
XPath in XSLT
<!-- *********** Resumes for People *********** -->
<PEOPLE>
<PERSON PERSONID="p2">
<NAME>Tracey Wilson</NAME>
<ADDRESS>121 Zootle Road, Cape Town, South Africa</ADDRESS>
<TEL>(++2721) 531 9090</TEL>
<FAX>(++2721) 531 9090</FAX>
<EMAIL>Tracey [email protected]</EMAIL>
</PERSON>
<PERSON PERSONID="p3">
<NAME>Jodie Foster</NAME>
<ADDRESS>30 Animal Road, New York, USA</ADDRESS>
<TEL>(++1) 3000 12345</TEL>
<FAX>(++1) 3000 12345</FAX>
<EMAIL>Jodie [email protected]</EMAIL>
</PERSON>
<PERSON PERSONID="p4">
<NAME>Lorrin Maughan</NAME>
<ADDRESS>1143 Winners Lane, London, UK</ADDRESS>
<TEL>(++94) 17 12345</TEL> <FAX>(++94) 17 12345</FAX>
<EMAIL>Lorrin [email protected]</EMAIL>
</PERSON>
<PERSON PERSONID="p5">
<NAME>Steve Rachel</NAME>
<ADDRESS>90210 Beverly Hills, California, USA</ADDRESS>
<TEL>(++1) 2000 12345</TEL> <FAX>(++1) 2000 12345</FAX>
<EMAIL>Steve [email protected]</EMAIL>
</PERSON>
</PEOPLE>
XPath in XSLT
eXtensible Stylesheet Language Transformation ...transform an XML file into an HTML file or another text-based format...
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE BORDER="2">
<TR>
<TD>Name</TD>
<TD>Address</TD>
Xpath Expression
<TD>Tel</TD>
<TD>Fax</TD>
<TD>Email</TD>
</TR>
<xsl:for-each select="PEOPLE/PERSON">
<TR>
<TD><xsl:value-of select="NAME"/></TD>
<TD><xsl:value-of select="ADDRESS"/></TD>
<TD><xsl:value-of select="TEL"/></TD>
<TD><xsl:value-of select="FAX"/></TD>
<TD><xsl:value-of select="EMAIL"/></TD>
</TR>
</xsl:for-each>
</TABLE></BODY></HTML>
</xsl:template>
</xsl:stylesheet>
XPath in XSLT
eXtensible Stylesheet Language Transformation ...transform an XML file into an HTML file or another text-based format...
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE BORDER="2">
<TR>
<TD>Name</TD>
<TD>Address</TD>
Xpath Expression
<TD>Tel</TD>
<TD>Fax</TD>
<TD>Email</TD>
</TR>
<xsl:for-each select="PEOPLE/PERSON[NAME='Tracey Wilson']">
<TR>
<TD><xsl:value-of select="NAME"/></TD>
<TD><xsl:value-of select="ADDRESS"/></TD>
<TD><xsl:value-of select="TEL"/></TD>
<TD><xsl:value-of select="FAX"/></TD>
<TD><xsl:value-of select="EMAIL"/></TD>
</TR>
</xsl:for-each>
</TABLE></BODY></HTML>
</xsl:template>
</xsl:stylesheet>
XPath in XSLT
eXtensible Stylesheet Language Transformation ...transform an XML file into an HTML file or another text-based format...
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<HTML>
<BODY>
<TABLE BORDER="2">
<TR>
<TD>Name</TD>
Xpath Expression
<TD>Address</TD>
<TD>Tel</TD>
<TD>Fax</TD>
<TD>Email</TD>
</TR>
<xsl:for-each select="PEOPLE/PERSON[3]">
<TR>
<TD><xsl:value-of select="NAME"/></TD>
<TD><xsl:value-of select="ADDRESS"/></TD>
<TD><xsl:value-of select="TEL"/></TD>
<TD><xsl:value-of select="FAX"/></TD>
<TD><xsl:value-of select="EMAIL"/></TD>
</TR>
</xsl:for-each>
</TABLE></BODY></HTML>
</xsl:template>
</xsl:stylesheet>
4th person
XPath in Java Applications
Where are the classes?
import org.w3c.dom.*;
import org.apache.xpath.*;
XPath in Java Applications
You first need an XML document
Convenience
public static Document getDoc(String file) { method
org.w3c.dom.Document doc = null;
System.out.println("Parsing XML file " + file);
try{
javax.xml.parsers.DocumentBuilderFactory docBuilderFactory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new File( file ));
doc.getDocumentElement().normalize();
return doc;
}catch (Exception e) {
System.out.println(e); e.printStackTrace();
return doc;
}
}
Note: the parse method's
alternative parms include :
InputSource,
InputStream, and
String uri
XPath in Java Applications
<PRODUCTS>
<PRODUCT ACCOUNT="1111111" id="111">
<DESCRIPTION>Alexander Apples</DESCRIPTION>
<PREVIOUSCOUNTDATE>2003-12-31</PREVIOUSCOUNTDATE>
<PREVIOUSCOUNT>10</PREVIOUSCOUNT>
Excerpt from <THISCOUNT>7</THISCOUNT>
<SOLD>27</SOLD>
an XML file <ADDED>24</ADDED>
<UOM>BAG</UOM>
<COST>10.10</COST>
<RETAIL>15.12</RETAIL>
<PRODUCTLOCATION>Counter-C01R01</PRODUCTLOCATION>
<SERIALNUMBER></SERIALNUMBER>
<MODEL>Fruit</MODEL>
<EXPIRATIONDATE>2003-12-31</EXPIRATIONDATE>
</PRODUCT>
<PRODUCT ACCOUNT="222222" id="222">
<DESCRIPTION>Baldwin Apples</DESCRIPTION>
<PREVIOUSCOUNTDATE>2003-12-31</PREVIOUSCOUNTDATE>
<PREVIOUSCOUNT>20</PREVIOUSCOUNT>
<THISCOUNT>13</THISCOUNT>
<SOLD>37</SOLD>
<ADDED>12</ADDED>
<UOM>BAG</UOM>
<COST>10.10</COST>
<RETAIL>15.12</RETAIL>
<PRODUCTLOCATION>Counter-C01R01</PRODUCTLOCATION>
<SERIALNUMBER></SERIALNUMBER>
<MODEL>Fruit</MODEL>
<EXPIRATIONDATE>2003-12-31</EXPIRATIONDATE>
</PRODUCT>
...
</PRODUCTS>
XPath in Java Applications
package com.MobileSales.test;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import org.apache.xpath.*;
Alexander Apples
2003-12-31
10
7
27
24
BAG
10.10
15.12
Counter-C01R01
Fruit
2003-12-31
XPath in Java Applications
public static void main(String[] args) {
String xPath = "/PRODUCTS/PRODUCT";
try{
System.out.println("Parsing XML file "+ fileToParse);
Document doc=com.MobileSales.Util.getDoc(new FileInputStream(fileToParse), fileToParse);
===============================================================================
Output:
Element org.w3c.dom.Document.getDocumentElement()
javax.xml.transform.Transformer serializer
= TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes");
System.out.println("subtree "+ xPath);
org.w3c.dom.traversal.NodeIterator nl = XPathAPI.selectNodeIterator(doc, xPath);
Node n;
while ((n = nl.nextNode()) != null) {
serializer.transform(
new javax.xml.transform.dom.DOMSource(n),
new javax.xml.transform.stream.StreamResult(System.out));
}
}catch(FileNotFoundException fne){System.out.println(fne + "\n File not found!");
}catch(javax.xml.transform.TransformerException te){System.out.println(te);}
}
void javax.xml.transform.Transformer.transform(
Source xmlSource, Result outputTarget)
throws TransformerException NodeIterators are used to step through
a set of nodes in a NodeList,
Process the source tree to the output result. the document subtree governed
Parameters: by a particular Node,
xmlSource The input for the source tree.
outputTarget The output target.
the results of a query,
Throws: or any other set of nodes.
TransformerException If an unrecoverable error occurs
during the course of the transformation.
XPath in Java Applications
Parsing XML file ./Data/Inventory_sample.xml
try{Document doc=
com.MobileSales.Util.getDoc(new FileInputStream(fileToParse), fileToParse);
n.getAttributes().getNamedItem("ACCOUNT")
.getNodeValue()
XPath in Java Servlets
public class AllInventoryTable extends HttpServlet {
String sql, dbDriver, dbURL, db2eTable="INVENTORY",
XMLFile="Data/Inventory_sample.xml";
Populate
+" '"+ product.getAttributes().getNamedItem("ACCOUNT").getNodeValue() +"'"
+" , CURRENT DATE "
+" , '"+ product.getAttributes().getNamedItem("id").getNodeValue() +"'"
+" , '"+ XPathAPI.eval(product,"DESCRIPTION") +"'"
database table +" , "+ XPathAPI.eval(product,"PREVIOUSCOUNT")
+" , "+ XPathAPI.eval(product,"THISCOUNT")
+" , "+ XPathAPI.eval(product,"SOLD")
JSTL version 1.1 works with JSP 2.0 and Servlet Spec 2.4
Use the Servlet 2.4 syntax in your web.xml (web-app deployment descriptor):
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"> ...
============================================================================
Do NOT use the Servlet 2.3 (or prior) deployment descriptor syntax:
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>...
The EL operators
Arithmetic
+, -, *, / (or div), % (or mod)
Relational
== (or eq), != (or ne), < (or lt), > (or gt), <= (or le), >= (or ge)
Logical
&& (or and), || (or or), ! (or not)
Validation
empty
JSTL (Java Standard Tag Library)
XML Tag Library
<x:out select=”XPathExpression” [escapeXml=”{true|false}”]/>
<x:if select=”XPathExpression”
[var=”varName”] [scope=”{page|request|session|application}”]> body content </x:if>
<x:choose>
<x:when select=”XPathExpr”> body content </x:when>
<x:otherwise>conditional block</x:otherwise>
</x:choose>
XML </STOP>
<TAXID>325478521</TAXID>
<MINORITY>35%</MINORITY>
<x:choose>
<x:when
select="$activityLogXML/LOG[WHERE=$custNum and contains(WHAT,'CLOS') and substring(WHEN,1,10)=$today]">
Edit/Re-open </x:when>
<x:when
select="$activityLogXML/LOG[WHERE=$custNum and substring(WHEN,1,10)=$today]">
Continue/Close </x:when>
XPath
<x:otherwise>
Start </x:otherwise>
</x:choose>
</a> </TD>
<TD> <x:out select="$STOP/@ACCOUNT"/> </TD>
<TD> <x:out select="$STOP/NAME"/> </TD>
<TD> <x:out select="$STOP/ADDRESS"/> </TD>
<TD> <x:out
</TR>
select="$STOP/CITY"/> </TD>
Choose/When
</x:forEach>
statement
...
<html><head> <title> Route Processing </title>
XPath
<TR>
<TH> Action </TH>
<TH> Account# </TH>
<TH> Name </TH>
<TH> Address </TH>
<TH> City </TH>
</TR>
<x:forEach var="STOP" select="$routesXML/ROUTES/ROUTE[@ID=$ROUTE_SELECTED]/STOP">
<TR><x:set var="custNum" select="$STOP/@ACCOUNT"/>
<TD> <a href='../VisitOpener?STOP_PARM=<x:out select="$STOP/NAME"/>&CUST_PARM=<x:out select="$STOP/@ACCOUNT"/>' >
<!-- when=<x:out select="$activityLogXML/LOG[substring(WHEN,1,8)]" /> -->
<x:choose>
<x:when select="$activityLogXML/LOG[WHERE=$custNum and contains(WHAT,'CLOS') and substring(WHEN,1,10)=$today]">
Edit/Re-open </x:when>
<x:when select="$activityLogXML/LOG[WHERE=$custNum and substring(WHEN,1,10)=$today]">
Continue/Close </x:when>
<x:otherwise>
Route
Start </x:otherwise>
</x:choose>
</a> </TD>
<TD> <x:out select="$STOP/@ACCOUNT"/> </TD>
<TD> <x:out select="$STOP/NAME"/>
<TD> <x:out select="$STOP/ADDRESS"/>
<TD> <x:out select="$STOP/CITY"/>
</TD>
</TD>
</TD>
“STOP”
</TR>
</x:forEach>
</TABLE>
Loop
</c:if>
</center></body></html>
XPath Links
www.w3.org/TR/xpath
www.w3schools.com/xpath/default.asp
javaalmanac.com/egs/org.w3c.dom/pkg.html
xml.apache.org/xalan-j/apidocs/org/apache/xpath/package-summary.html
java.sun.com/j2se/1.5.0/docs/api/javax/xml/xpath/package-summary.html