如何将XML文档转换为Java对象(或数组)? 我像这样重写XML:
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File("file.xml"));
doc.getDocumentElement().normalize();
现在我想将XML作为Object(或Array),但我该怎么做呢? 是否有任何方法或教程或课程可以做到这一点?
答案 0 :(得分:9)
使用XStream。
对象到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);
生成的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
Person newJoe = (Person)xstream.fromXML(xml);
另见
答案 1 :(得分:6)
答案 2 :(得分:3)
我建议使用XStream进行XML(反)序列化。它比使用Java的内置XML API更简单方式。
答案 3 :(得分:1)
我会看一下JAX / B,它提供了一种在Java对象和XML表示之间“绑定”的方法。
我对使用基于Rational Eclipse的工具here进行了一次小小的描述,但似乎也有(自己从未使用过)直接的Eclipse插件,例如this
确实可以手工编写JAX / B,对复杂的XML有点沉闷,但注释很容易。
答案 4 :(得分:0)
我使用Simple XML并且发现它非常简单和强大。我不熟悉XStream,但是Simple允许您使用注释控制XML模式,这给您带来了很大的自由。写这篇文章的人总是对他的邮件列表做出回应。