XPath 1.0 queries on JAXB objects?

2019-02-03 14:12发布

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?

标签: java xpath jaxb
2条回答
Anthone
2楼-- · 2019-02-03 14:37

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);
查看更多
家丑人穷心不美
3楼-- · 2019-02-03 14:59

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.

查看更多
登录 后发表回答