XPath 1.0查询JAXB对象?

JC *_*rds 9 java xpath jaxb

JAXB非常棒,真正节省时间,但遍历生成的对象树仍然非常耗时; 几乎与直接使用DOM一样糟糕.

有没有办法可以在JAXBElement上执行XPath 1.0查询,而不必每次都精心地将文档编组到DOM模型中?

ska*_*man 13

不直接,没有.但是,您可以使用Apache Commons Jxpath,它允许您跨任意对象图运行XPath查询,而不仅仅是JAXB绑定的.它可以在"宽松"模式下运行,该模式可以容忍空值.

非常方便替换那些易于NPE的图导航.


Ara*_*ram 8

接受的答案是从2010年开始,这篇文章是为了那些希望将XPath与JAXB一起使用的人的利益.Moxy实现提供了许多很好的扩展,其中一个是执行XPath.在Moxy的教程中阅读更多相关信息.从同一个地方复制的示例

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);
Run Code Online (Sandbox Code Playgroud)