2

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?

3
  • 2
    What kind of object do you need and what kind of XML file do you have? You need to clarify more, otherwise the answer is "You did it!", since Document is an Object and has been built from an XML file. Commented Dec 14, 2010 at 15:54
  • what do u mean by "I want that XML as Object", so what is doc?, can u describe exactly what u want? Commented Dec 14, 2010 at 16:00
  • Sorry for that mistake, I should better say (just) array. Commented Dec 14, 2010 at 16:28

5 Answers 5

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

life.java: I've seen the XStream tutorial. If you want to see something cool, check out this MOXy example demonstrating XPath based mapping (I'm the tech lead): bdoughan.blogspot.com/2010/09/…
@Blaise Doughan Ah, Misunderstood your comment, Thanks nice stuff.
6

You will need JAXB unmarshaling.

Comments

3

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

2 Comments

No problem. Also JAXB is a standard so there are multiple implementations: Metro (the RI included in Java SE 6), EclipseLink MOXy (I'm the tech lead), and JaxMe
1

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.

Comments

0

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.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.