Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.*;

public class Main {
    public static String toXML(Object obj) {
        StringBuffer xml = new StringBuffer();
        StringBuffer space = new StringBuffer();
        toXMLCycle(obj, xml, space);

        StringBuffer result = new StringBuffer();
        result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
        result.append(
                "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\r\n");
        result.append("<plist version=\"1.0\">\r\n");
        result.append(xml);
        return result.toString();
    }

    private static void toXMLCycle(Object element, StringBuffer xml, StringBuffer space) {
        if (element instanceof Map) {
            Map map = (Map) element;

            xml.append(space);
            xml.append("<dict>\r\n");
            space.append("  ");
            for (Object key : map.keySet()) {
                xml.append(space);
                xml.append("<key>");
                xml.append(key.toString());
                xml.append("</key>\r\n");

                Object value = map.get(key);
                toXMLCycle(value, xml, space);
            }

            space.delete(0, 2);
            xml.append(space);
            xml.append("</dict>\r\n");

        } else if (element instanceof List) {
            xml.append(space);
            xml.append("<array>\r\n");
            space.append("  ");

            List list = (List) element;
            for (Object item : list) {
                toXMLCycle(item, xml, space);
            }

            space.delete(0, 2);
            xml.append(space);
            xml.append("</array>\r\n");

        } else {
            xml.append(space);
            xml.append("<string>");
            xml.append(element.toString());
            xml.append("</string>\r\n");
        }
    }
}