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.List;
import java.util.Map;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Returns all direct simple text value subnodes and their values for a dataNode
     *
     * Example XML: <dataNode> <a>1</a> <b>2</b> <c>3</c> </dataNode> Returns: a=1, b=2, c=3.
     *
     * @param dataNode
     *            the data node
     * @return the simple values of node
     */
    public static Map<String, String> getSimpleValuesOfNode(Node dataNode) {
        Map<String, String> returnMap = new HashMap<String, String>();

        NodeList list = dataNode.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.TEXT_NODE
                    && node.getChildNodes().getLength() == 1) {
                returnMap.put(node.getNodeName(), node.getFirstChild().getNodeValue());
            }
        }

        return returnMap;
    }

    public static List<Node> getChildNodes(Node dataNode) {
        List<Node> returnList = new ArrayList<Node>();

        NodeList list = dataNode.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getNodeType() != Node.TEXT_NODE) {
                returnList.add(node);
            }
        }

        return returnList;
    }

    /**
     * Gets a node value.
     *
     * @param pNode
     *            the p node
     * @return the node value
     */
    public static String getNodeValue(Node pNode) {
        if (pNode.getNodeValue() != null) {
            return pNode.getNodeValue();
        } else if (pNode.getFirstChild() != null) {
            return getNodeValue(pNode.getFirstChild());
        } else {
            return null;
        }
    }
}