How to evaluate XPath Expression using Saxon?
How to evaluate XPath Expression using Saxon?
This article is part of a tutorial.
Tutorial Index page - XPath Expression Evaluation
Introduction
An XML Parser is a parser that is designed to read XML and create a way for programs to use XML. Some of the most popular parsers found are
- SAX (Simple API for XML)
- DOM (Document Object Model)
Difference between SAX & DOM Parsers
The simple difference between the two types of parsers are
SAX
- Event Based
- Goes through XML line by line
- Read only
DOM
- Tree Based
- Places entire XML document into memory
- Iterate, read and write
Anyway, That was a simple introduction about the parsers. Our focus today is about how we can evaluate an XPathExpression in an XML or XSLT Document using Saxon processor
XPathEvaluator
net.sf.saxon.sxpath.XPathEvaluator: This class provides Saxon API for evaluation of the XPath expressions. you can instantiate a default constructor or construct XPathEvaluator with a given Configuration.
XPathEvaluator oXpathEvaluator = new XPathEvaluator(); XPathEvaluator oXpathEvaluator = new XPathEvaluator(Configuration config);
Once XPathEaluator is constructed, now build the source document from the input XML/XSLT document using thr build() method
XMLSource oSource = new XMLSource(new File("sourcefile.xml")); oXpathEvaluator.build(javax.xml.transform.Source oSource);
build() method is deprecated since 8.9, you can this instead
Configuration.buildDocument(javax.xml.transform.Source)
Next, we create the XPathExpression
XPathExpression
net.sf.saxon.sxpath.XPathExpression: This class is a representation of XPath Expression which is used with the XPathEvaluator for evaluation.
Consider, you want to extract a particular attribute from the root node from the example xslt below.
The expression to find the root node would be
XpathExpression oXPathExpression = oXpathEvaluator.createExpression("\*");
References
Feedback or Questions?
We welcome feedback and questions and will try our best to attend to it as quickly as possible!
Please note that you would have to register before you can post in our forums and this is purely to guard us from the spam-bots. Be assured that we do not send spam mails and our website registration only takes minutes.
