Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: XML to Object (or Array)

Tags:

java

object

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?

like image 359
Poru Avatar asked Jun 12 '26 09:06

Poru


1 Answers

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

like image 91
jmj Avatar answered Jun 14 '26 23:06

jmj