开发者

Java: XML to Object (or Array)

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("fil开发者_如何学Ce.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?


Use XStream.

Object to 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:

<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);

Also see

  • Reference

  • Simple


You will need JAXB unmarshaling.


I recommend using XStream for XML (de)serialization. It's way simpler than using Java's built-in XML APIs.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜