Saliya's Blogs

Mostly technical stuff with some interesting moments of life

XPath with Axiom

6 comments
Apache Axiom, which is the popular open source StAX based XML infoset model, supports XPath out of the box. If you ever want to know how to use this feature, WSO2 Oxygentank has a very nice tutorial.

The tricky part is, how to work with Namespaces? To get an idea on to the matter consider the following XML document.



The following code fragment will retrieve the ns1:c1 element and the two ns2:color attributes of each element.

// root is the document
OMElement root = builder.getDocumentElement();

AXIOMXPath xpath = new AXIOMXPath("//a:c1");
xpath.addNamespace("a", "http://namespace1.com");
OMElement c1 = (OMElement)xpath.selectSingleNode(root);
System.out.println(c1);

xpath = new AXIOMXPath("//@b:color");
xpath.addNamespace("b", "http://namespace2.com");
List colors = xpath.selectNodes(root);
System.out.println(colors.get(0).getAttributeValue());
System.out.println(colors.get(1).getAttributeValue());

The important line in this code is the xpath.addNamespace(prefix, uri) method. This prefix doesn't have to be the exact prefix used in the actual document (which in fact is not known in most cases).

That's it, have fun with Axiom :)

6 comments :

Post a Comment