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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With