Java:XML 到对象(或数组)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4441017/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:23:32  来源:igfitidea点击:

Java: XML to Object (or Array)

javaxmlobject

提问by Poru

How could I convert a XML Document to a Java Object (or Array)? I readed the XML like this:

如何将 XML 文档转换为 Java 对象(或数组)?我像这样阅读了 XML:

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?

现在我想要那个 XML 作为对象(或数组)但是我应该怎么做?是否有任何方法、教程或课程可以做到这一点?

回答by Jigar Joshi

Use XStream.

使用XStream

Object to XML

对象到 XML

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);

The resulting XML looks like this:

生成的 XML 如下所示:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>    

XML to Object

XML 到对象

Person newJoe = (Person)xstream.fromXML(xml);

Also see

另见

回答by yegor256

You will need JAXB unmarshaling.

您将需要JAXB 解组

回答by Matt Ball

I recommend using XStreamfor XML (de)serialization. It's waysimpler than using Java's built-in XML APIs.

我建议使用XStream进行 XML(反)序列化。它的方法比使用Java的内置XML的API简单。

回答by djna

I would look at JAX/B, which gives a way to "bind" between Java objects and XML representations.

我会看看 JAX/B,它提供了一种在 Java 对象和 XML 表示之间“绑定”的方法。

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.

我有一个小写了Rational基于Eclipse的工具做它的位置,但似乎(从来没有使用过自己)直Eclipse插件太多,比如这个

Indeed writing JAX/B by hand is possible, gets a bit dull for complex XML, but annotations are quite easy.

确实,手动编写 JAX/B 是可能的,对于复杂的 XML 来说有点枯燥,但是注释很容易。

回答by AlanObject

I have used Simple XMLand 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.

我使用过Simple XML并发现它非常简单和强大。我对 XStream 不太熟悉,但 Simple 允许您使用注释来控制 XML 模式,这为您提供了很大的自由。写它的人总是在他的邮件列表上做出回应。