Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.*;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static Map<String, String> XmlAsMap(Node node) {
        Map<String, String> map = new HashMap<String, String>();
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.hasAttributes()) {
                for (int j = 0; j < currentNode.getAttributes().getLength(); j++) {
                    Node item = currentNode.getAttributes().item(i);
                    if (item != null)
                        map.put(item.getNodeName(), prepare(item.getTextContent()));
                }
            }
            if (currentNode.getFirstChild() != null) {
                if (currentNode.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
                    map.putAll(XmlAsMap(currentNode));
                } else if (currentNode.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                    map.put(currentNode.getLocalName(), prepare(currentNode.getTextContent()));
                }
            }
        }
        return map;
    }

    private static String prepare(String unprepared) {
        return unprepared.replaceAll("\\s{2,}", "").replaceAll("\\n", "");
    }
}