Searching...
Saturday, 8 March 2014

XML to Java object using XMLDecoder Example

06:24

XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean.
The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like ObjectInputStream. Here is one simple example to convert a java object to xml String and xml String to Java object

1. Create a java bean (Customer.java)

package com.pretech;
public class Customer {
	private String name;
	private String address;
	public Customer() {
	}
	public Customer(String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}
//Getters and Setters

2. Create a main class to convert java object to xml

package com.pretech;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class ExlDecoderExample {
	public static void main(String[] args) {
		Customer c1 = new Customer("Pretech", "Bangalore");
		
		String customerXml=objectToXML(c1);
		System.out.println("Customer xml data :" +customerXml );
		System.out.println("Customer object data :" + XMLToObject(customerXml));
	}
	public static String objectToXML(Object voObj) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		XMLEncoder xmlEncoder = null;
		try {
			xmlEncoder = new XMLEncoder(new BufferedOutputStream(stream));
			xmlEncoder.writeObject(voObj);
			xmlEncoder.close();
			return stream.toString("UTF-8");
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
	public static Object XMLToObject(String dataXML) {
		XMLDecoder d = null;
		try {
			d = new XMLDecoder(new ByteArrayInputStream(
					dataXML.getBytes("UTF-8")));
			Object voObj = d.readObject();
			d.close();
			return voObj;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
}

3.Output

Customer xml data :<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_04" class="java.beans.XMLDecoder">
 <object class="com.pretech.Customer">
  <void property="address">
   <string>Bangalore</string>
  </void>
  <void property="name">
   <string>Pretech</string>
  </void>
 </object>
</java>
Customer object data :Customer [name=Pretech, address=Bangalore]

Ref: http://www.oracle.com/technetwork/java/persistence4-140124.html

0 comments: