woodhead92 woodhead92 - 1 year ago 72
Java Question

Creating an XML document using Java

I have seen many programs where XML documents can be created using Java with specified fields. I am yet to come across one where the user gets to decide the names of the rootElement's and the childEelement's. Does anyone know how to go about this?

Answer Source

Use XStream

Java Code

XStream xstream = new XStream();
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

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

Output 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>

Library: http://x-stream.github.io/tutorial.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download