Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath 1.0 queries on JAXB objects?

Tags:

java

jaxb

xpath

JAXB has been great, a real timesaver, but it's still really time consuming to traverse the resulting object trees; almost as bad as working directly with the DOM.

Is there a way that I can do XPath 1.0 queries on a JAXBElement, without having to painstakingly marshal the document to and from a DOM model each time?

like image 265
JC Richards Avatar asked Jun 22 '10 08:06

JC Richards


2 Answers

Not directly, no. However, you can use Apache Commons Jxpath, which allows you to run XPath queries across arbitrary object graphs, not just JAXB-bound ones. It can be run in "lenient" mode, which is tolerant of nulls.

Extremely handy for replacing those NPE-prone graph navigations.

like image 67
skaffman Avatar answered Nov 04 '22 06:11

skaffman


The accepted answer was from 2010 and this post is for the benefit of others who are looking to use XPath with JAXB. Moxy implementation provides lots of nice extensions and one of them is to execute XPath. Read more about this on Moxy's tutorial. Example copied from the same place

Customer customer = (Customer) jaxbContext.createUnmarshaller().unmarshal(instanceDoc);
...
int customerId = jaxbContext.getValueByXPath(customer, "@id", null, Integer.class);
jaxbContext.setValueByXPath(customer, "first-name/text()", null, "Bob");
jaxbContext.setValueByXPath(customer, "phone-number/area-code/text()", null, "555");
...
jaxbContext.createMarshaller().marshal(customer, System.out);
like image 28
Aravind Yarram Avatar answered Nov 04 '22 05:11

Aravind Yarram