How do I convert a JavaBean to an XML String using XMLEncoder?
Author: Deron Eriksson
Description: This Java tutorial shows how to write a JavaBean to an XML String representation using Java's XMLEncoder class.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
In another tutorial, we saw how we could use the XMLEncoder class to save a JavaBeanW object to an XMLW file. Suppose we'd rather convert the JavaBean to a String representation rather than to a file. To do this, we can have the XMLEncoder write to a ByteArrayOutputStream rather than a FileOutputStream. The XmlEncodeToString class demonstrates this. It creates a MyBean object, populates it with some data, and then the XMLEncoder class writes the object to a ByteArrayOutputStream. The ByteArrayOutputStream is converted to a String via a call to its toString() method. Then, this String is output to standard output. XmlEncodeToString.javapackage example; import java.beans.XMLEncoder; import java.io.ByteArrayOutputStream; import java.util.Vector; public class XmlEncodeToString { public static void main(String[] args) throws Exception { MyBean mb = new MyBean(); mb.setMyBoolean(true); mb.setMyString("xml is cool"); Vector<String> v = new Vector<String>(); v.add("one"); v.add("two"); v.add("three"); mb.setMyVector(v); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLEncoder xmlEncoder = new XMLEncoder(baos); xmlEncoder.writeObject(mb); xmlEncoder.close(); String xml = baos.toString(); System.out.println(xml); } } The MyBean class is shown here: MyBean.javapackage example; import java.io.Serializable; import java.util.Vector; public class MyBean implements Serializable { private static final long serialVersionUID = 1L; private boolean myBoolean; private String myString; private Vector<String> myVector; public MyBean() { } public boolean isMyBoolean() { return myBoolean; } public void setMyBoolean(boolean myBoolean) { this.myBoolean = myBoolean; } public String getMyString() { return myString; } public void setMyString(String myString) { this.myString = myString; } public Vector<String> getMyVector() { return myVector; } public void setMyVector(Vector<String> myVector) { this.myVector = myVector; } } Executing XmlEncodeToString results in the following console output: Console Output<?xml version="1.0" encoding="UTF-8"?> <java version="1.5.0_09" class="java.beans.XMLDecoder"> <object class="example.MyBean"> <void property="myBoolean"> <boolean>true</boolean> </void> <void property="myString"> <string>xml is cool</string> </void> <void property="myVector"> <object class="java.util.Vector"> <void method="add"> <string>one</string> </void> <void method="add"> <string>two</string> </void> <void method="add"> <string>three</string> </void> </object> </void> </object> </java> Related Tutorials:
|