Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate XML (in String representation) in java

Tags:

java

xml

I have defined a java class, but only need to output some of the fields of this class into an XML. The returned type must be a String. I first opted for the easiest way using a StringBuffer. However, when I tried to process the output String represenation, it failed. I think it is mostly likely because there are some characters that are not encoded in the UTF-8 in the input. Could someone tell me what is the best way to handle this? Thanks.

like image 933
flyingfromchina Avatar asked Jun 11 '10 15:06

flyingfromchina


3 Answers

Give XStream a try.

Quote:

Let's create an instance of Person and populate its fields:

 Person joe = new Person("Joe", "Walnes");
 joe.setPhone(new PhoneNumber(123, "1234-456"));
 joe.setFax(new PhoneNumber(123, "9999-999")); 

Now, to convert it to XML, all you have to do is make a simple call to XStream:

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> 

It's that simple. Look at how clean the XML is.

like image 91
bakkal Avatar answered Oct 06 '22 01:10

bakkal


I'm partial to XOM myself, but there are a lot of good third-party XML tools for Java out there. The important things to remember are that 1) hand-rolling your own XML with String or StringBuffer or the like is the sort of thing that always comes back to bite you and 2) Java's built-in XML utilities are over-engineered and not at all pleasant to work with. (Though they're still an improvement over constructing the XML string manually.) Grabbing a good third-party package is the way to go.

like image 36
BlairHippo Avatar answered Oct 06 '22 01:10

BlairHippo


You may use Java Architecture for XML Binding (or simply JAXB) - with annotations it should be extremely easy and elegant.

In the simplest case, all you have to do, is just add @XmlRootElement annotation to the bean you want to serialize into XML

@XmlRootElement
class Foo{
..
}

and marshall the bean into a formatted string

StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(Foo.class);
Marshaller m = context.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); 
m.marshal(individual, writer);

By default, the Marshaller will use UTF-8 encoding when generating XML data to a java.io.OutputStream, or a java.io.Writer.

like image 38
Vasil Remeniuk Avatar answered Oct 06 '22 02:10

Vasil Remeniuk