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

public class Main {
    public static String getElementValue(Element parent, String tagName) {
        Element element = getElement(parent, tagName);
        return element != null ? element.getTextContent() : null;
    }

    public static String getElementValue(Element element) {
        if (element != null) {
            NodeList nodes = element.getChildNodes();
            if (nodes != null && nodes.getLength() > 0) {
                for (int i = 0; i < nodes.getLength(); ++i) {
                    Node node = nodes.item(i);
                    if (node instanceof Text) {
                        return ((Text) node).getData();
                    }
                }
            }
        }

        return null;
    }

    public static Element getElement(Element parent, String tagName) {
        List children = getElements(parent, tagName);
        return children.isEmpty() ? null : (Element) children.get(0);
    }

    public static List<Element> getElements(Element parent, String tagName) {
        NodeList nodes = parent.getElementsByTagName(tagName);
        ArrayList elements = new ArrayList();

        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                elements.add((Element) node);
            }
        }

        return elements;
    }
}