beans

Bean XML serialization

This is an example of how to serialize a java Bean using the XMLEncoder. The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. Serializing a java Bean using the XMLEncoder implies that you should:

  • Create a simple class, like Bean class in the example. It has two String properties and getters and setters for the properties.
  • Create a FileOutputStream stream, initialized with a String name of the target xml file.
  • Create a new XMLEncoder, with a new BufferedOutputStream to write data to the FileOutputStream.
  • Use writeObject(Object o) API method of XMLEncoder to write an XML representation of the specified object to the output.
  • Use close() API method to close the output stream associated with this stream.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class BeanXMLSerialization {
	
	public static void main(String[] args) throws Exception {
		
		Bean bean = new Bean();
		bean.setProperty1("value1");
		bean.setProperty2(2);

		// Serialize object into XML
	    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("out.xml")));
	    encoder.writeObject(bean);
	    encoder.close();
		
	}
	
	public static class Bean {
		
		// Property property1
		private String property1;
	    // Property property2
		private int property2;
	    
		public String getProperty1() {
			return property1;
		}
		public void setProperty1(String property1) {
			this.property1 = property1;
		}
		
		public int getProperty2() {
			return property2;
		}
		public void setProperty2(int property2) {
			this.property2 = property2;
		}
	    
	}

}

Output:

<?xml version="1.0" encoding="UTF-8"?> 
<java version="1.6.0_05" class="java.beans.XMLDecoder"> 
 <object class="com.javacodegeeks.snippets.core.BeanXMLSerialization$Bean"> 
  <void property="property1"> 
   <string>value1</string> 
  </void> 
  <void property="property2"> 
   <int>2</int> 
  </void> 
 </object> 
</java>

 
This was an example of how to serialize a java Bean using the XMLEncoder in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button