|
How to serialize a bean to XML |
|
|
This Java tip demonstrates a method of serializing a bean to XML. A Bean persists by having
its properties, fields, and state information saved and restored to and from storage. The
mechanism that makes persistence possible is called serialization. JavaBeans uses
the JDK's object serialization API for its serialization needs.
// Create an object and set properties
MyClass obj = new MyClass();
obj.setProp(1);
obj.setProps(new int[]{1, 2, 3});
try {
// Serialize object into XML
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
encoder.writeObject(o);
encoder.close();
} catch (FileNotFoundException e) {
}
// This class defines two properties - prop and props
public class MyClass {
// The prop property
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
// The props property
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
}
|
Here is the XML data:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.0" class="java.beans.XMLDecoder">
<object class="MyClass">
<void property="prop">
<int>1</int>
</void>
<void property="props">
<array class="int" length="3">
<void index="0">
<int>1</int>
</void>
<void index="1">
<int>2</int>
</void>
<void index="2">
<int>3</int>
</void>
</array>
</void>
</object>
</java>
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.