Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.LinkedHashMap;

import java.util.Map;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;

import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Map<String, String> attrbiuteToMap(NamedNodeMap attributes) {
        if (attributes == null)
            return new LinkedHashMap<String, String>();
        Map<String, String> result = new LinkedHashMap<String, String>();
        for (int i = 0; i < attributes.getLength(); i++) {
            result.put(attributes.item(i).getNodeName(), attributes.item(i).getNodeValue());
        }
        return result;
    }

    public static String getNodeValue(Node node) {
        if (node instanceof Comment) {
            return null;
        }
        if (node instanceof CharacterData) {
            return ((CharacterData) node).getData();
        }
        if (node instanceof EntityReference) {
            return node.getNodeValue();
        }
        if (node instanceof Element) {
            return getTextValue((Element) node);
        }
        return node.getNodeValue();
    }

    /**
     * Extract the text value from the given DOM element, ignoring XML comments. <p>Appends all CharacterData nodes and
     * EntityReference nodes into a single String value, excluding Comment nodes.
     *
     * @see CharacterData
     * @see EntityReference
     * @see Comment
     */
    public static String getTextValue(Element valueEle) {
        if (valueEle == null)
            throw new IllegalArgumentException("Element must not be null");
        StringBuilder sb = new StringBuilder();
        NodeList nl = valueEle.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node item = nl.item(i);
            if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
                sb.append(item.getNodeValue());
            } else if (item instanceof Element) {
                sb.append(getTextValue((Element) item));
            }
        }
        return sb.toString();
    }
}