Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: LGPL 

import java.util.ArrayList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Node[] getChildNodes(final Node node, final String attributeName, final String value) {
        final ArrayList nodeList = new ArrayList();
        final NodeList childs = node.getChildNodes();
        String readValue = null;
        for (int i = 0; i < childs.getLength(); i++) {
            readValue = getAttribute(childs.item(i), attributeName);
            if (value.equals(readValue)) {
                nodeList.add(childs.item(i));
            }
        } //next child node
        final Node[] result = new Node[nodeList.size()];
        nodeList.toArray(result);
        return result;
    }

    public static Node[] getChildNodes(final Node node, final String elementName) {
        final ArrayList nodeList = new ArrayList();
        final NodeList childs = node.getChildNodes();
        String nodeName = null;
        for (int i = 0; i < childs.getLength(); i++) {
            nodeName = childs.item(i).getNodeName();
            if (nodeName != null && nodeName.equals(elementName)) {
                nodeList.add(childs.item(i));
            }
        } //next child node
        final Node[] result = new Node[nodeList.size()];
        nodeList.toArray(result);
        return result;
    }

    public static String getAttribute(final Node node, final String attributeName) {
        final NamedNodeMap tmpMap = node.getAttributes();
        if (tmpMap == null) {
            return null;
        }
        final Node tmpNode = tmpMap.getNamedItem(attributeName);
        if (tmpNode == null) {
            return null;
        }
        return tmpNode.getNodeValue();
    }

    public static String[] getAttributes(final Node node, final String[] attributeNames) {
        final String[] valueList = new String[attributeNames.length];
        final NamedNodeMap attMap = node.getAttributes();
        Node tmpNode = null;
        for (int i = 0; i < attributeNames.length; i++) {
            try {
                tmpNode = attMap.getNamedItem(attributeNames[i]);
                valueList[i] = tmpNode.getNodeValue();
            } catch (Exception e) {
                valueList[i] = "";
            }
        } // next attribute
        return valueList;
    }
}