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 :

  1. Aren't you missing some casts to OMElement?

    ReplyDelete
  2. Ah! thanks for the point.

    ReplyDelete
  3. Thanks, this was very helpful

    ReplyDelete
  4. This was very help to me at a very critical time :)
    Thanks Saliya!!!

    ReplyDelete
  5. This is a great blog post! Just helped me save lots of time. It's amazing how useful this blog post is even it's as old as 2008!

    ReplyDelete
  6. It really made my day.Thanks Saliya!.

    ReplyDelete