How to evaluate XPath Expression using Saxon?

Given a large XML or XSLT document, How can you parse the doc and iterate to a particular node, access its attribute etc? The keyword is XPathExpression. But first if you are not able to decide which parser to choose for processing the document and extracting the required meaningful data, heres a small introduction to some of the most popular XML parsers....

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

  1. Event Based
  2. Goes through XML line by line
  3. Read only

DOM

  1. Tree Based
  2. Places entire XML document into memory
  3. 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

http://www.saxonica.com/documentation/

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.