Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    @SuppressWarnings("rawtypes")
    public static String map2Xml(Map map, String encode, String root) {
        StringBuffer sb = new StringBuffer();
        sb.append("<" + root + ">");// <?xml version=\"1.0\"
        // encoding=\""+encode+"\"?>
        mapToXml(map, sb);
        sb.append("</" + root + ">");
        try {
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("rawtypes")
    private static void mapToXml(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value instanceof List) {
                ArrayList list = (ArrayList) map.get(key);
                // sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    sb.append("<" + key + ">");
                    // Object listi = list.get(i);
                    if (list.get(i) instanceof HashMap) {
                        HashMap hm = (HashMap) list.get(i);
                        // sb.append("<" + key + ">");
                        mapToXml(hm, sb);
                        // sb.append("</" + key + ">");
                    } else {
                        // sb.append("<" + key + ">" + list.get(i) + "</" + key
                        // + ">");
                        sb.append(list.get(i));
                    }
                    // else
                    // if(listi.getClass().getName().equals("java.util.ArrayList")){
                    // sb.append("<" + key + ">" + "??" + "</" + key + ">");}

                    sb.append("</" + key + ">");
                }
                // sb.append("</" + key + ">");

            } else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
                    mapToXml((HashMap) value, sb);
                    sb.append("</" + key + ">");
                } else {
                    sb.append("<" + key + ">" + value + "</" + key + ">");
                }

            }

        }
    }
}