WSO2Con 2013 CFP Banner

How Can I Evaluate an XPath with AXIOM?

By Eran Chinthaka
Date: Fri, 22nd Sep, 2006
Level:
Reads: 12542 Discuss this article on Stack Overflow

Apache AXIOM has in-built support for evaluating XPath expressions. Let's see how we can accomplish this.

chinthaka's picture
Eran Chinthaka
Software Engineer
WSO2 Inc.

You need to download an AXIOM release. We encourage you to use Axiom 1.1.1, as it is the latest, most stable version. Once you download the release, extract it to a folder. Then add all the jars found inside "build" and "lib" folders in to your classpath. Now let's get in to the real work.

Let's take following XML as an example.

<Persons>
<Person>
<Name>Dihini Himahansi< /Name>


<Sex>Female</Sex>
<Address>
<City>Rajagiriya</City>
<District>Colombo</District>
<Country>Sri Lanka</Country>
</Address>
</Person>
<Person>
<Name>Thushari Damayanthi</Name>
<Sex>Female</Sex>
<Address>
<City>Ambalangoda</City>
<District>Galle</District>
<Country>Sri Lanka</Country>
</Address>
</Person>
</Persons>

Let's try to get access to all the person elements of this XML fragment. So the xpath will be "/Persons/Person"

Step 1

We need to create an OMElement from the source XML. Let's create an OMBuilder to build AXIOM tree, passing an InputStream from the source xml to the builder.

OMElement documentElement = new
StAXOMBuilder(inStreamToXML).getDocumentElement();

Step 2

Create an instance of AXIOMXpath, passing your xpath expression.

AXIOMXPath xpathExpression = new AXIOMXPath ("/Persons/Person"); 

Step 3

Apply the xpath on the OMElement created in step 1.

List nodeList = (OMNode)
xpathExpression.selectNodes(documentElement);

We've asked AXIOMXPath to return all the matching nodes. But a single node can be selected by calling selectSingleNode() method, which provides the first matching element.

You can download the complete code sample.

OMNode is the base class of all the information items implemented in AXIOM. It can be an Element, Text, Comment, Processing Instruction, etc. If you want to just see what is returned, you can always call the toString() method of OMNode to see what it is. For more information on working with OMNodes and AXIOM, please refer OM Tutorial.

Applies To:

Apache AXIOM/Java 1.1.1

More Information:

AXIOM Tutorial on official web site :http://ws.apache.org/commons/axiom/OMTutorial.html

Introducing AXIOM :http://www.theserverside.com/tt/articles/article.tss?l=Axiom

WSO2Con 2014