Tuesday, September 17, 2013

Build xml using java code from hashmap

Download XmlBuilder.java class

Follow the following link to parse all type of xml file to map/list


package xmlparser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Pritom K Mondal
 * @created 28th August 2014
 */
public class XmlBuilder {
    private Map dataMap;
    private String xmlString = "";
    private static final String NEW_LINE = "\n";
    private static final String MATCHER_REPLACE = "[^0-9a-zA-Z:\\.]+";
    private static final String MATCHER_1 = "[a-zA-Z:\\_](.*)";
    
    public static void main(String[] args) {
        Map dataMap = new HashMap();
        for(int index = 1; index <= 2; index ++) {
            HashMap tempMap = new HashMap();
            tempMap.put("id", index);
            tempMap.put("name", "Name: " + index);
            tempMap.put("roll", "Roll: " + index);
            
            HashMap attMap = new HashMap();
            attMap.put("id", index * 10);
            attMap.put("attr-name", "Name == " + (index * 20));
            tempMap.put("<<attributes>>", attMap);  

            dataMap.put("user" + index, tempMap);
        }
        
        List dataList = new ArrayList();
        for (int index = 0; index < 2; index++) {
            HashMap tempMap = new HashMap();
            tempMap.put("id", index);
            tempMap.put("name", "Name: " + index);
            tempMap.put("roll", "Roll: " + index);

            dataList.add(tempMap);
        }
        dataMap.put("listMap", dataList);

        HashMap resultMap = new HashMap();
        resultMap.put("success", true);
        resultMap.put("message", "Thank you for generating this XML.");
        resultMap.put("dataMap", dataMap);
        resultMap.put("dataList", dataList);
        
        Map finalMap = new HashMap();
        finalMap.put("rootTag", resultMap);
        
        String xmlString = new XmlBuilder(finalMap).toXML();
        System.out.println(xmlString);
    }

    XmlBuilder(Map dataMap) {
        this.dataMap = dataMap;
    }

    public String toXML() {
        /*System.out.println(this.dataMap);*/
        this.renderMapAsXml(this.dataMap, "data", 0);
        /*System.out.println(this.xmlString);*/
        return this.xmlString;
    }
    
    private void renderListAsXml(List dataList, String wrapper, int cycle) {
        wrapper = wrapper.trim();
        if (!wrapper.matches(MATCHER_1)) {
            wrapper = "obj_" + wrapper;
        }
        for (int index = 0; index < dataList.size(); index++) {
            Object dataMapValue = dataList.get(index);
            if (dataMapValue instanceof List) {
                this.xmlString += this.makeTabSpace(cycle - 1) + "<" + wrapper + '>' + NEW_LINE;
                this.renderListAsXml((List) dataMapValue, wrapper, cycle + 1);
                this.xmlString += this.makeTabSpace(cycle - 1) + "</" + wrapper + '>' + NEW_LINE;
            }
            else if (dataMapValue instanceof Map || dataMapValue instanceof HashMap) {
                this.renderMapAsXml((Map) dataMapValue, wrapper, cycle);
                this.xmlString += NEW_LINE;
            }
            else {
                this.xmlString += this.makeTabSpace(cycle - 1) + "<" + wrapper + "><![CDATA[";
                this.xmlString += dataMapValue;
                this.xmlString += "]]></" + wrapper + '>' + NEW_LINE;
            }
        }
    }

    private void renderMapAsXml(Map dataMap, String wrapper, int cycle) {
        if (cycle == 0) {
            this.xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NEW_LINE;
        }
        wrapper = "" + wrapper;
        wrapper = wrapper.trim();
        if (!wrapper.matches(MATCHER_1)) {
            wrapper = "obj_" + wrapper;
        }
        wrapper = wrapper.replaceAll(MATCHER_REPLACE, "_");
        if (cycle > 0) {
            this.xmlString += this.makeTabSpace(cycle - 1) + '<' + wrapper;
        }
        for (Object object : dataMap.entrySet()) {
            Map.Entry entry = (Map.Entry) object;
            Object dataMapKey = entry.getKey();
            Object dataMapValue = entry.getValue();
            if (dataMapKey.toString().equalsIgnoreCase("<<attributes>>")) {
                Map attributeMap = (Map) dataMapValue;
                for (Object objectAttribute : attributeMap.entrySet()) {
                    Map.Entry entryAttribute = (Map.Entry) objectAttribute;
                    this.xmlString += " " + entryAttribute.getKey() + "='" + entryAttribute.getValue() + "'";
                }
            }
        }
        if (cycle > 0) {
            this.xmlString += '>' + NEW_LINE;
        }
        int otherTags = 0;
        try {
            for (Object object : dataMap.entrySet()) {
                Map.Entry entry = (Map.Entry) object;
                Object dataMapKey = entry.getKey();
                Object dataMapValue = entry.getValue();

                if (!dataMapKey.toString().equalsIgnoreCase("<<attributes>>")) {
                    if (dataMapValue instanceof List) {
                        this.renderListAsXml((List) dataMapValue, "" + dataMapKey, cycle + 1);
                        otherTags++;
                    } 
                    else if (dataMapKey.toString().startsWith("<<")) {
                        this.xmlString = this.xmlString.substring(0, this.xmlString.length() - this.NEW_LINE.length());
                        this.xmlString += "<![CDATA[";
                        this.xmlString += dataMapValue + "]]>";
                    }
                    else if (dataMapValue instanceof Map || dataMapValue instanceof HashMap) {
                        this.renderMapAsXml((HashMap) dataMapValue, "" + dataMapKey, cycle + 1);
                        this.xmlString += NEW_LINE;
                        otherTags++;
                    }
                    else {
                        dataMapKey = "" + dataMapKey;
                        dataMapKey = dataMapKey.toString().trim();
                        if (!dataMapKey.toString().matches(MATCHER_1)) {
                            dataMapKey = "obj_" + dataMapKey;
                        }
                        dataMapKey = dataMapKey.toString().replaceAll(MATCHER_REPLACE, "_");
                        if (dataMapValue != null) {
                            dataMapValue = "" + dataMapValue;
                            dataMapValue = dataMapValue.toString().replaceAll("]]>", "]]&gt;");
                        }
                        this.xmlString += this.makeTabSpace(cycle);
                        this.xmlString += ('<' + dataMapKey.toString() + "><![CDATA[");
                        this.xmlString += dataMapValue + "]]></";
                        this.xmlString += dataMapKey.toString() + '>' + NEW_LINE;
                        otherTags++;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (cycle > 0) {
            this.xmlString += this.makeTabSpace(otherTags == 0 ? otherTags : cycle - 1) + "</" + wrapper + ">";
        }
    }

    private String makeTabSpace(int numberOfTabs) {
        String returnString = "";
        for (int index = 1; index <= numberOfTabs; index ++) {
            returnString += "    ";
        }
        return returnString;
    }
}

Output would be as following:


<?xml version="1.0" encoding="UTF-8" ?>
<rootTag>
    <dataList>
        <id><![CDATA[0]]></id>
        <roll><![CDATA[Roll: 0]]></roll>
        <name><![CDATA[Name: 0]]></name>
    </dataList>
    <dataList>
        <id><![CDATA[1]]></id>
        <roll><![CDATA[Roll: 1]]></roll>
        <name><![CDATA[Name: 1]]></name>
    </dataList>
    <message><![CDATA[Thank you for generating this XML.]]></message>
    <dataMap>
        <user2 id='20' attr-name='Name == 40'>
            <id><![CDATA[2]]></id>
            <roll><![CDATA[Roll: 2]]></roll>
            <name><![CDATA[Name: 2]]></name>
        </user2>
        <user1 id='10' attr-name='Name == 20'>
            <id><![CDATA[1]]></id>
            <roll><![CDATA[Roll: 1]]></roll>
            <name><![CDATA[Name: 1]]></name>
        </user1>
        <listMap>
            <id><![CDATA[0]]></id>
            <roll><![CDATA[Roll: 0]]></roll>
            <name><![CDATA[Name: 0]]></name>
        </listMap>
        <listMap>
            <id><![CDATA[1]]></id>
            <roll><![CDATA[Roll: 1]]></roll>
            <name><![CDATA[Name: 1]]></name>
        </listMap>
    </dataMap>
    <success><![CDATA[true]]></success>
</rootTag>

No comments:

Post a Comment