Java Bean to XML conversion

In this article lets discuss about how to convert a Java bean to XML document.

Have look at the following Java bean.

Device.java

public class Device
{

        public Device(long deviceId, String deviceName, String productId, String serialNo)
        {
                super();
                this.deviceId = deviceId;
                this.deviceName = deviceName;
                this.productId = productId;
                this.serialNo = serialNo;
        }

        public Device()
        {

        }

        private long    deviceId;
        private String  deviceName;
        private String  productId;
        private String  serialNo;

        /**
         * @return the deviceId
         */

        public long getDeviceId()
        {
                return deviceId;
        }

        /**
         * @param deviceId
         *            the deviceId to set
         */

        public void setDeviceId(long deviceId)
        {
                this.deviceId = deviceId;
        }

        /**
         * @return the deviceName
         */

        public String getDeviceName()
        {
                return deviceName;
        }

        /**
         * @param deviceName
         *            the deviceName to set
         */

        public void setDeviceName(String deviceName)
        {
                this.deviceName = deviceName;
        }

        /**
         * @return the productId
         */

        public String getProductId()
        {
                return productId;
        }

        /**
         * @param productId
         *            the productId to set
         */

        public void setProductId(String productId)
        {
                this.productId = productId;
        }

        /**
         * @return the serialNo
         */

        public String getSerialNo()
        {
                return serialNo;
        }

        /**
         * @param serialNo
         *            the serialNo to set
         */

        public void setSerialNo(String serialNo)
        {
                this.serialNo = serialNo;
        }
}

Consider a scenario where you want to convert the above bean to an XML document as follows.

<Devices>
<Device>
   <deviceId>1001</deviceId>
   <deviceName>Cables Connectors</deviceName>
   <productId>CC1084</productId>
   <serialNo>038123-45627</serialNo>
</Device>
</Devices>

Here fields in the Java bean will be converted as child tags inside the tag.

We can create an xml document in Java using DOM api. DOM - Document Object Model is a standard or specification from W3Consortium. It specifies interfaces which can be used to access and update HTML/XML documents. We are going to use Xerces.jar and Xalan.jar which provide DOM implementation and xml serialization.

Have a look at the below class.

BeanToXML.java

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

import org.apache.xerces.dom.DOMImplementationImpl;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class BeanToXML
{

        /**
         * @param args
         * @throws Exception
         */

        public static void main(String[] args) throws Exception
        {

                DomParser dp = new DomParser();
                ArrayList lstDev = new ArrayList();
                Device dev1 = new Device(1001, "Cables Connectors", "CC1084", "038123-45627");
                Device dev2 = new Device(1002, "Circuit Breakers", "CC1085", "038123-45727");
                Device dev3 = new Device(1003, "Control Power Transformers", "CC1086", "038123-45827");
                Device dev4 = new Device(1004, "Copper Rotor Motors", "CC1087", "038123-45629");
                Device dev5 = new Device(1005, "Couplings, Flender Brand", "CC1088", "038123-45927");

                lstDev.add(dev1);
                lstDev.add(dev2);
                lstDev.add(dev3);
                lstDev.add(dev4);
                lstDev.add(dev5);

                dp.createDoc(lstDev, "Devices");

        }

        public void createDoc(ArrayList objLst, String rootElementName) throws Exception
        {

                Document dom = DOMImplementationImpl.getDOMImplementation().createDocument(null, null, null);
                Element root = dom.createElement(rootElementName);

                for (Object obj : objLst)
                {
                        String className = obj.getClass().getCanonicalName();

                        Element child = dom.createElement(className.substring(className.lastIndexOf(".") + 1, className.length()));
                        Field[] fields = obj.getClass().getDeclaredFields();
                        for (Field f : fields)
                        {
                                Element child11 = dom.createElement(f.getName());
                                Method method = obj.getClass().getMethod(getMethodName(f.getName()), null);

                                child11.setTextContent(method.invoke(obj, new Object[0]).toString());

                                child.appendChild(child11);
                        }
                        root.appendChild(child);
                }

                dom.appendChild(root);

                XMLSerializer serial = new XMLSerializer(System.out, null);
                try
                {
                        serial.serialize(dom.getDocumentElement());
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }
        }

        public String getMethodName(String mName)
        {
                if (mName != null)
                {
                        mName = Character.toUpperCase(mName.charAt(0)) + mName.substring(1);
                        mName = "get" + mName;
                        return mName;
                }
                else
                {
                        return "";
                }
        }
}

We need a pass an array list of java beans of same type to the createDoc() method, which will create the xml document out of the list of beans. The fieldNames and field values are retrieved using java reflection api.

Here is the sample output.

<?xml version="1.0"?>
<Devices>
<Device>
        <deviceId>1001</deviceId>
        <deviceName>Cables Connectors</deviceName>
        <productId>CC1084</productId>
        <serialNo>038123-45627</serialNo>
</Device>
<Device>
        <deviceId>1002</deviceId>
        <deviceName>Circuit Breakers</deviceName>
        <productId>CC1085</productId>
        <serialNo>038123-45727</serialNo>
</Device>
<Device>
        <deviceId>1003</deviceId>
        <deviceName>Control Power Transformers</deviceName>
        <productId>CC1086</productId>
        <serialNo>038123-45827</serialNo>
</Device>
<Device>
        <deviceId>1004</deviceId>
        <deviceName>Copper Rotor Motors</deviceName>
        <productId>CC1087</productId>
        <serialNo>038123-45629</serialNo>
</Device>
<Device>
<deviceId>1005</deviceId>
        <deviceName>Couplings, Flender Brand</deviceName>
        <productId>CC1088</productId>
        <serialNo>038123-45927</serialNo>
</Device>
</Devices>
Technology: 

Search