XPath 1.0 queries on JAXB objects?

2019-02-03 13:52发布

问题:

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?

回答1:

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.



回答2:

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);


标签: java xpath jaxb