More XPATH and XSLT - PowerPoint PPT Presentation

About This Presentation
Title:

More XPATH and XSLT

Description:

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; ... import org.apache.xpath.XPathAPI; import org.w3c.dom.traversal. ... – PowerPoint PPT presentation

Number of Views:351
Avg rating:3.0/5.0
Slides: 45
Provided by: mm77
Category:
Tags: xpath | xslt | more | reimport

less

Transcript and Presenter's Notes

Title: More XPATH and XSLT


1
More XPATH and XSLT
  • Xpath and Namespaces
  • Xpath Programming in Java
  • XSLT Default Rules
  • XSLT Programming in Java

2
Xpath and Namespaces
  • Namespaces are widely used
  • In a SOAP message, for example, every element is
    qualified
  • with a namespace
  • Here we will look at how namespaces are handled
    in XPath

3
Xpath and Namespaces
Consider an Xpath expression /Envelope/Header/Si
gnature Now, with namespaces included /SOAP-ENV
Envelope/SOAP-ENVHeader/dsigSignature What is
wrong with this approach? Namespace
prefixes may vary. SEEnvelope is a legal
SOAP element if the prefix SE is associated
with http//schemas.xmlsoap.org/soap/envelope
4
Xpath and Namespaces
Suppose we want to select all the Signature
elements associated with the namespace
http//www.w3.org/2000/09/xmldsig Write the
Xpath expression as follows //namespace-uri()
http//www.w3.org/2000/09/xmldsig and
local-name() Signature
5
Xpath Programming in Java
  • We can evaluate an Xpath expression from within
    a
  • Java program.
  • The following is an example using Namespaces.

6
XPathTest.java
lt?xml version"1.0" encoding"UTF-8"?gt ltSignature
Id"MyFirstSignature" xmlns
"http//www.w3.org/2000/0
9/xmldsig"gt ltSignedInfogt
ltCanonicalizationMethod Algorithm
"http//www.w3.org/TR/2001/REC-xml-c14n-2001031
5"/gt ltSignatureMethod Algorithm
"http//www.w3.org/2000/09/xmldsigdsa-sh
a1"/gt ltReference URI
"http//www.w3.org/TR/2000/REC-xhtml1-20000126/"gt
ltTransformsgt ltTransform
Algorithm "http//www.w3.org/
TR/2001/REC-xml-c14n-20010315"/gt
lt/Transformsgt
7
ltDigestMethod Algorithm
"http//www.w3.org/2000/09/xmldsigsha1
"/gt ltDigestValuegtj6lwx3rvEPO0vKtMup4NbeV
u8nk lt/DigestValuegt lt/Referencegt
lt/SignedInfogt
8
XPathTest.java
// XML and Java Second Ed. Chapter 7 // For
JAXP import javax.xml.parsers.DocumentBuilder imp
ort javax.xml.parsers.DocumentBuilderFactory impo
rt org.xml.sax.InputSource // For Xalan XPath
API import org.apache.xpath.XPathAPI import
org.w3c.dom.traversal.NodeIterator import
org.w3c.dom.Node import org.w3c.dom.Document
9
public class XPathTest public static void
main(String args) throws Exception
String xmlFilePath args0 String
xPath args1 System.out.println("Inpu
t XML File " xmlFilePath)
System.out.println("XPath " xPath)
DocumentBuilderFactory factory
DocumentBuilderFactory.newInstance()
factory.setNamespaceAware(true)
DocumentBuilder parser factory.newDocumentBuilde
r() InputSource in new
InputSource(xmlFilePath) Document doc
parser.parse(in)
10
Node contextNode doc.getDocumentElement()
NodeIterator i
XPathAPI.selectNodeIterator(contextNode, xPath)
int count 0 Node node
// For each node while ((node
i.nextNode()) ! null) // Outputs
the node to System.out
System.out.println(node.toString())
count System.out.println(""
count " match(es)")
11
Example Run
D\McCarthy\www\95-733\examples\xpath\HandleNamesp
acesgt java XPathTest MyFirstSignature.xml
"//local-name()'DigestValue' and
namespace-uri() 'http//www.w3.org/2000/09/xmldsi
g' Input XML File MyFirstSignature.xml XPath
//local-name()'DigestValue' and
namespace-uri() 'http//www.w3.org/2000/09/xmldsi
g' ltDigestValuegtj6lwx3rvEPO0vKtMup4NbeVu8nklt/D
igestValuegt 1 match(es)
12
XSLT Default Rules
ltxsltemplate match-/gt
ltxslapply-templatesgt lt/xsltemplategt ltxsltempla
te matchtext() _at_gt ltxslvalue-of
select./gt lt/xsltemplategt ltxsltemplate
matchprocessing-instruction() comment() /gt
13
XSLT Programming in Java
Two important interfaces to represent the XML and
XSLT documents javax.xml.transform
Interface Source All Known Implementing
Classes DOMSource, SAXSource,
StreamSource javax.xml.transform
Interface Result All Known Implementing
Classes DOMResult, SAXResult,
StreamResult
14
XSLT Programming in Java
A Factory to build XSLT Transformers javax.xml.t
ransform Class TransformerFactory Ask for a
Transformer with an associated XSLT document
Transformer t newTransformer(Source sou
rce) Use t to do the transformation voidtransfo
rm(Source xmlSource, Result outputTarget)
          Process the source tree to the output
result.
15
XSLT Stream to Stream Example
// XML and Java Chapter 7 import
javax.xml.transform.TransformerFactory import
javax.xml.transform.Transformer import
javax.xml.transform.stream.StreamSource import
javax.xml.transform.stream.StreamResult public
class XSLTStreamTest public static void
main(String args) throws Exception //
args0 specifies the path to the input XSLT
stylesheet String xsltURL args0
// args1 specifies the path to the input XML
document String xmlURL args1
16
// Creates instances of StreamSource for
the stylesheet StreamSource xslt new
StreamSource(xsltURL) // Creates
instances of StreamSource for the input document
StreamSource xml new StreamSource(xmlURL)
// Creates an instance of
TransformerFactory TransformerFactory
factory TransformerFactory.newInstan
ce() // Creates an instance of
Transformer Transformer transformer
factory.newTransformer(xslt) // Executes
the Transformer transformer.transform(xml,
new StreamResult(System.out))
17
XSLT DOM to DOM Example
// XML and Java Chapter 7 import
javax.xml.transform.TransformerFactory import
javax.xml.transform.Transformer import
javax.xml.transform.dom.DOMSource import
javax.xml.transform.dom.DOMResult import
javax.xml.parsers.DocumentBuilder import
javax.xml.parsers.DocumentBuilderFactory import
org.apache.xml.serialize.OutputFormat import
org.apache.xml.serialize.XMLSerializer import
org.w3c.dom.Node import org.w3c.dom.Element impo
rt org.w3c.dom.Document import
org.w3c.dom.DocumentFragment
18
public class XSLTDOMTest public static void
main(String args) throws Exception //
args0 specifies the path to the input XSLT
stylesheet String xsltURL args0
// args1 specifies the path to the input XML
document String xmlURL args1
// Creates an instance of DocumentBuilderFactory.
DocumentBuilderFactory dFactory
DocumentBuilderFactory.newInstance()
dFactory.setNamespaceAware(true) //
Creates an instance of DocumentBuilder
DocumentBuilder parser dFactory.newDocumentBuild
er()
19
// Creates a DOM instance of the
stylesheet Document xsltDoc
parser.parse(xsltURL) // Creates a DOM
instance of the input document Document
xmlDoc parser.parse(xmlURL) //
Creates an instance of TransformerFactory
TransformerFactory tFactory
TransformerFactory.newInstance() //
Checks if the factory supports DOM or not
if(!tFactory.getFeature(DOMSource.FEATURE)
!tFactory.getFeature(DOMResult.FEATURE))
throw new Exception("DOM is not
supported")
20
// Creates instances of DOMSource and
DOMResult DOMSource xsltDOMSource new
DOMSource(xsltDoc) DOMSource
xmlDOMSource new DOMSource(xmlDoc)
DOMResult domResult new DOMResult()
// Creates an instance of Transformer
Transformer transformer
tFactory.newTransformer(xsltDOMSource)
// Executes the Transformer
transformer.transform(xmlDOMSource, domResult)
// Gets the result Node resultNode
domResult.getNode()
21
// Prints the response
OutputFormat formatter new OutputFormat()
formatter.setPreserveSpace(true)
XMLSerializer serializer new
XMLSerializer(System.out, formatter)
switch (resultNode.getNodeType()) case
Node.DOCUMENT_NODE
serializer.serialize((Document)resultNode)
break case Node.ELEMENT_NODE
serializer.serialize((Element)resultNode)
break case
Node.DOCUMENT_FRAGMENT_NODE
serializer.serialize((DocumentFragment)resultNode)
break default
throw new Exception("Unexpected node type")

22
SAX Event Translation Using XSLT
Suppose we have a SAX handler written for a
particular type of XML document. Suppose too
that we have a new document with
similar semantics but with a different
structure. We dont want to modify our old
handler. Instead we want to do a translation of
the new document to the old format.
23
JAXP/SAX
SAX
JAXP/SAX
SAX
SAXParser
Application
TransformerHandler
(3) Register
(2) Register
Content Handler
SAX Result
SAX Parser
Content Handler
Input XML
SAX Events
Transform
SAX Events
(4)
(5)
(7)
(6)
Register (1)
XSLT
24
Books.xml
lt?xml version"1.0" encoding"UTF-8"?gt ltBooks
xmlns"http//www.example.com/xmlbook2/chap07/"gt
ltBookgt ltPublishedDategt16 November
1999lt/PublishedDategt ltAuthorgt
ltAuthorNamegtJames Clarklt/AuthorNamegt
ltContactTogtjjc_at_jclark.comlt/ContactTogt
lt/Authorgt ltAuthorgt
ltAuthorNamegtSteve DeRoselt/AuthorNamegt
ltContactTogtSteven_DeRose_at_Brown.edult/ContactTogt
lt/Authorgt lt/Bookgt
25
ltBookgt ltPublishedDategt16 November
1999lt/PublishedDategt ltAuthorgt
ltAuthorNamegtJames Clarklt/AuthorNamegt
ltContactTogtjjc_at_jclark.comlt/ContactTogt
lt/Authorgt lt/Bookgt lt/Booksgt
26
We have a handler for Books.xml
// Adapted from XML and Java Chapter 7 import
java.util.Vector import org.xml.sax.Attributes i
mport org.xml.sax.SAXException import
org.xml.sax.helpers.DefaultHandler // Imports
for main() to test the Handler import
org.xml.sax.InputSource import
org.xml.sax.XMLReader import javax.xml.parsers.SA
XParser import javax.xml.parsers.SAXParserFactory

27
public class BookHandler extends
DefaultHandler // An array to store the
results final Vector books public
BookHandler() this.books new
Vector() // Instance variables
temporarily used for processing Book
currentBook null Author currentAuthor
null StringBuffer buf new
StringBuffer()
28
class Book String publishedDate
Vector authors new Vector() public
String toString() return
("Book(publishedDate" publishedDate
", authors" authors")")
class Author String
authorName String contactTo
public String toString() return
("Author(authorName" authorName
", contactTo" contactTo ")")

29
public void endDocument() throws SAXException
System.out.println(books)
public void startElement(String uri,String
localName, String qName,
Attributes attributes)
throws SAXException if
("Book".equals(qName)) currentBook
new Book() return

30
if ("Author".equals(qName))
currentAuthor new Author()
return buf.setLength(0)
public void endElement(String uri,
String localName,
String qName) throws SAXException
if ("Book".equals(qName))
books.addElement(currentBook)
return
31
if ("Author".equals(qName))
currentBook.authors.addElement(currentAuthor)
return if
("PublishedDate".equals(qName))
currentBook.publishedDate buf.toString()
else if ("AuthorName".equals(qName))
currentAuthor.authorName buf.toString()
else if ("ContactTo".equals(qName))
currentAuthor.contactTo buf.toString()
buf.setLength(0)
32
public void characters(char ch, int start,
int length) throws SAXException
buf.append(new String(ch, start, length))
public static void main(String args)
throws Exception // Create and
InputSource on a book.xml document
InputSource xml new InputSource(args0)
// Creates a SAX parser
SAXParserFactory pFactory SAXParserFactory.newIn
stance() SAXParser parser
pFactory.newSAXParser() XMLReader
xmlReader parser.getXMLReader()
33
// Set up this class as the handler
xmlReader.setContentHandler(new BookHandler())
// Parses the input XML (which is
of the appropriate form)
xmlReader.parse(xml)
34
D..\examples\XSLTFiltergt java BookHandler
Books.xml Book(publishedDate16 November 1999,
authors Author(authorNameJames
Clark, contactTojjc_at_jclark.com),
Author(authorNameSteve DeRose,
contactToSteven_DeRose_at_Brown.edu)),
Book(publishedDate16 November 1999,
authors Author(authorNameJames Clark,
contactTojjc_at_jclark.com))
35
But no handler for sample.xml
lt?xml version"1.0" encoding"UTF-8"?gt ltW3Cspecs
xmlns"http//www.example.com/xmlbook2/chap07/"gt
ltspec title"XML Path Language (XPath) Version
1.0" url"http//www.w3.org/TR/xpath"gt
ltdate type"REC"gt16 November 1999lt/dategt
lteditorsgt lteditorgt ltnamegtJames
Clarklt/namegt ltemailgtjjc_at_jclark.comlt/emailgt
lt/editorgt
36
lteditorgt ltnamegtSteve DeRoselt/namegt
ltemailgtSteven_DeRose_at_Brown.edult/emailgt
lt/editorgt lt/editorsgt lt/specgt ltspec
title"XSL Transformations (XSLT) Version 1.0"
url"http//www.w3.org/TR/xslt"gt ltdate
type"REC"gt16 November 1999lt/dategt lteditorsgt
lteditorgt ltnamegtJames Clarklt/namegt
ltemailgtjjc_at_jclark.comlt/emailgt
lt/editorgt lt/editorsgt lt/specgt lt/W3Cspecsgt
37
We write an XSLT program
lt?xml version"1.0" encoding"UTF-8"?gt ltxslstyles
heet version"1.0" xmlnsxsl"http//www.w3.or
g/1999/XSL/Transform" xmlns"http//www.example.
com/xmlbook2/chap07/"gt ltxsloutput method"xml"
encoding"UTF-8"/gt ltxsltemplate
match"local-name()'W3Cspecs'"gt
ltBooksgtltxslapply-templates/gtlt/Booksgt
lt/xsltemplategt
38
ltxsltemplate match"local-name()'spec'"gt
ltBookgtltxslapply-templates/gtlt/Bookgt
lt/xsltemplategt ltxsltemplate
match"local-name()'date'"gt
ltPublishedDategtltxslapply-templates/gtlt/PublishedDa
tegt lt/xsltemplategt ltxsltemplate
match"local-name()'editor'"gt
ltAuthorgtltxslapply-templates/gtlt/Authorgt
lt/xsltemplategt ltxsltemplate
match"local-name()'name'"gt
ltAuthorNamegtltxslapply-templates/gtlt/AuthorNamegt
lt/xsltemplategt
39
ltxsltemplate match"local-name()'email'"gt
ltContactTogtltxslapply-templates/gtlt/ContactTogt
lt/xsltemplategt ltxsltemplate match"_at_"gt
ltxslvalue-of select"name()"/gtltxslvalue-of
select"."/gt lt/xsltemplategt lt/xslstylesheetgt

In book but no need.
40
And write a program to pipe the XSLT output to
BookHandler.java
import javax.xml.parsers.SAXParser import
javax.xml.parsers.SAXParserFactory import
javax.xml.transform.TransformerFactory import
javax.xml.transform.sax.SAXSource import
javax.xml.transform.sax.SAXResult import
javax.xml.transform.sax.SAXTransformerFactory imp
ort javax.xml.transform.sax.TransformerHandler im
port javax.xml.transform.stream.StreamSource impo
rt org.xml.sax.InputSource import
org.xml.sax.XMLReader
41
public class XSLTSAXTest public static
void main(String args) throws Exception
// args0 specifies the URI for the XSLT
stylesheet String xsltURL args0
// args1 specifies the URI for the input XML
document String xmlURL args1
// Creates a stream source for the stylesheet
StreamSource xslt new StreamSource(xsltURL)
// Creates an input source for the
input document InputSource xml new
InputSource(xmlURL)
42
// Creates a SAX parser
SAXParserFactory pFactory SAXParserFactory.newIn
stance() pFactory.setNamespaceAware(true)
SAXParser parser pFactory.newSAXParser
() XMLReader xmlReader
parser.getXMLReader() // Creates an
instance of TransformerFactory
TransformerFactory tFactory
TransformerFactory.newInstance() //
Checks if the TransformingFactory supports SAX or
not if (!tFactory.getFeature(SAXSource.FEA
TURE)) throw new Exception("SAX is
not supported")
43
// Casts TransformerFactory to
SAXTransformerFactory SAXTransformerFactor
y stFactory ((SAXTransformerFactory)
tFactory) // Creates a
TransformerHandler with the stylesheet
TransformerHandler tHandler
stFactory.newTransformerHandler(xslt) //
Sets the TransformerHandler to the SAXParser
xmlReader.setContentHandler(tHandler)
// Sets the application ContentHandler //
to the TransformerHandler
tHandler.setResult(new SAXResult(new
BookHandler())) // Parses the input
XML xmlReader.parse(xml)
44
D..\examples\XSLTSAXFiltergt java XSLTSAXTest
sample-4.xsl sample.xml Book(publishedDate16
November 1999, authorsAuthor(authorNameJames
Clark, contactTojjc_at_jclark.com),
Author(authorNameSteve DeRose,
contactToSteven_DeRose_at_Brown.edu)), Book(publi
shedDate16 November 1999, authorsAuthor(author
NameJames Clark, contactTojjc_at_jclark.com))
Write a Comment
User Comments (0)
About PowerShow.com