How do I write a JavaBean to an XML file using XMLEncoder?
Author: Deron Eriksson
Description: This Java tutorial shows how to write a JavaBean to an XML file 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)


Page: < 1 2

(Continued from page 1)

After executing XmlEncodeToFile, the "mybean.xml" file is present at the root level of my project.

'mybean.xml' has been written

If we examine the "mybean.xml" file, we can see that it contains the data from the MyBean object.

mybean.xml

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

In another tutorial, we'll see how to read data back from the XMLW file into a JavaBeanW object. In another tutorial, we can see how to convert the JavaBean to a String rather than to a File.

Page: < 1 2