如何通过 XPath 将 XML 映射到 Java 对象?
给定 XML 示例:
<fooRoot>
<bar>
<lol>LOLOLOLOL</lol>
</bar>
<noob>
<boon>
<thisIsIt></thisIsIt>
</boon>
</noob>
</fooRoot>
应映射到:
class MyFoo {
String lol;
String thisIsIt;
Object somethingUnrelated;
}
约束:
- XML 不应被转换,它作为已解析的 org.w3c.dom.Document 对象提供。
- 类不会也不会 1:1 映射到 XML。
- 我只对将 XML 的特定路径映射到对象的特定字段感兴趣。
我梦想的解决方案是这样的:
@XmlMapped
class MyFoo {
@XmlElement("/fooRoot/bar/lol")
String lol;
@XmlElement("/noob/boon/thisIsIt")
String thisIsIt;
@XmlIgnore
Object somethingUnrelated;
}
是否有同样存在的东西?我发现要么需要严格的 1:1 映射(例如 JMX、JAXB),要么需要对所有字段进行手动迭代(例如 SAX、Commons Digester)
。 html" rel="nofollow">JiBX 绑定定义 最接近我想要的。然而,该工具用于编组/解组 Java 对象的完整层次结构。我只想在运行时将 XML 文档的一部分提取到现有的 Java bean 中。
Given the XML example:
<fooRoot>
<bar>
<lol>LOLOLOLOL</lol>
</bar>
<noob>
<boon>
<thisIsIt></thisIsIt>
</boon>
</noob>
</fooRoot>
Which should be mapped to:
class MyFoo {
String lol;
String thisIsIt;
Object somethingUnrelated;
}
Constraints:
- XML should not be transformed, it is provided as a parsed org.w3c.dom.Document object.
- Class does not and will not map 1:1 to the XML.
- I'm only interested to map specific paths of the XML to specific fields of the object.
My dream solution would look like:
@XmlMapped
class MyFoo {
@XmlElement("/fooRoot/bar/lol")
String lol;
@XmlElement("/noob/boon/thisIsIt")
String thisIsIt;
@XmlIgnore
Object somethingUnrelated;
}
Does anything likewise exists? What I've found either required a strict 1:1 mapping (e.g. JMX, JAXB) or manual iteration over all fields (e.g. SAX, Commons Digester.)
JiBX binding definitions come the nearest to what I'm lokking for. However, this tool is ment to marshall/unmarshall complete hierarchy of Java objects. I only would like to extract parts of an XML document into an existing Java bean at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:我是EclipseLink JAXB (MOXy) JAXB 2 的领导者和成员(JSR-222)专家组。
您可以使用 MOXy 执行此操作:
了解更多信息
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You can do this with MOXy:
For More Information
尝试 XStream。这非常简单。希望有帮助!我现在没有时间提供完整的示例:)
Try XStream. It's super easy. Hope it helps! I don't have time now for a full example :)
一种选择是编写自定义注释,它将 XPath 表达式作为输入并进行绑定。
One option could be write a custom annotation which will take the XPath expression as input and do the bindings.