Java:XML 到对象(或数组)
如何将 XML 文档转换为 Java 对象(或数组)? 我是这样读取 XML 的:
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
现在我想要将该 XML 作为对象(或数组),但是我应该如何执行此操作? 有没有任何方法、教程或课程可以做到这一点?
How could I convert a XML Document to a Java Object (or Array)?
I readed the XML like this:
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
Now I want that XML as Object (or Array) but how should I do this?
Are there any methods or tutorials or classes out there to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用XStream。
对象到 XML
生成的 XML 如下所示:
XML 到对象
另请参阅
参考
简单
简单
Use XStream.
Object to XML
The resulting XML looks like this:
XML to Object
Also see
Reference
Simple
您将需要 JAXB 解组。
You will need JAXB unmarshaling.
我建议使用 XStream 进行 XML(反)序列化。它比使用 Java 的内置 XML API方式简单。
I recommend using XStream for XML (de)serialization. It's way simpler than using Java's built-in XML APIs.
我会考虑 JAX/B,它提供了一种在 Java 对象和 XML 表示之间“绑定”的方法。
我有一篇关于使用基于 Rational Eclipse 的工具来完成此操作的小文章 这里,但似乎也有(我自己从未使用过)直接的 Eclipse 插件,例如 这个。
事实上,手动编写 JAX/B 是可能的,对于复杂的 XML 来说有点乏味,但是注释非常容易。
I would look at JAX/B, which gives a way to "bind" between Java objects and XML representations.
I've got a tiny write-up of doing it with Rational Eclipse-based tooling here, but there appear to be (never used them myself) straight Eclipse plugins too, for example this.
Indeed writing JAX/B by hand is possible, gets a bit dull for complex XML, but annotations are quite easy.
我使用过 Simple XML 并发现它非常简单且功能强大。我对 XStream 不太熟悉,但 Simple 允许您使用注释来控制 XML 模式,这给您很大的自由度。写它的人总是在他的邮件列表中做出回应。
I have used Simple XML and have found it quite easy and powerful. I am not as familiar with XStream, but Simple lets you control your XML schema using annotations which gives you a lot of freedom. The guy who writes it is always responsive on his mailing list.