java 对 JAXB 对象的 XPath 1.0 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3091354/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XPath 1.0 queries on JAXB objects?
提问by JC Richards
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.
JAXB 非常棒,真正节省了时间,但遍历生成的对象树仍然非常耗时;几乎和直接使用 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?
有没有一种方法可以在 JAXBElement 上执行 XPath 1.0 查询,而不必每次都费力地将文档编组到 DOM 模型或从 DOM 模型编组?
回答by skaffman
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.
不直接,不。但是,您可以使用Apache Commons Jxpath,它允许您跨任意对象图运行 XPath 查询,而不仅仅是 JAXB 绑定的对象图。它可以在“宽松”模式下运行,该模式可以容忍空值。
Extremely handy for replacing those NPE-prone graph navigations.
非常方便地替换那些容易出现 NPE 的图形导航。
回答by Aravind Yarram
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
接受的答案来自 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);

