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.List;

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

public class Main {
    public static String findElementText(Node node, String childTag) {
        if (node == null)
            return null;
        Node n = findNode(node, childTag);
        if (n != null)
            return n.getTextContent().trim();
        return null;
    }

    public static Node findNode(Node root, String tag) {
        if (root != null && root.getLocalName() != null && root.getLocalName().equals(tag)) {
            return root;
        }
        NodeList nodeList = root.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);
            Node firstNode = findNode(childNode, tag);
            if (firstNode != null) {
                return firstNode;
            }
        }
        return null;
    }

    public static List<Node> getChildNodes(Node node, String childTag) {
        ArrayList<Node> nodes = new ArrayList<Node>();
        if (node == null)
            return nodes;
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);
            if (childNode != null && childNode.getLocalName() != null
                    && childNode.getLocalName().equals(childTag)) {
                nodes.add(childNode);
            }
        }
        return nodes;
    }
}