Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;

import org.w3c.dom.Element;

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

public class Main {
    public static Boolean getElementBooleanValue(Element parentElement, String childElementName) {
        return getElementBooleanValue(parentElement, childElementName, false);
    }

    public static Boolean getElementBooleanValue(Element parentElement, String childElementName,
            boolean defaultValue) {
        Element childElement = getChildElement(parentElement, childElementName);
        if (childElement == null) {
            return defaultValue;
        }
        return getBooleanValue(childElement);
    }

    public static Element getChildElement(Element parent, String childName) {
        ArrayList<Element> childElements = getChildElements(parent, childName);
        return childElements.size() > 0 ? childElements.get(0) : null;
    }

    public static boolean getBooleanValue(Element booleanElement) {
        String elementValue = getTextContent(booleanElement);
        return Boolean.valueOf(elementValue);
    }

    public static ArrayList<Element> getChildElements(Element parent) {
        return getChildElements(parent, null);
    }

    public static ArrayList<Element> getChildElements(Element parent, String childName) {
        ArrayList<Element> childElements = new ArrayList<Element>();
        NodeList childNodes = parent.getChildNodes();

        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                if (childName == null || childNode.getNodeName().equals(childName)) {
                    childElements.add((Element) childNode);
                }
            }
        }

        return childElements;
    }

    private static String getTextContent(Element element) {
        if (element == null) {
            return null;
        }
        Node textNode = element.getFirstChild();
        if (textNode == null) {
            return "";
        }
        if (textNode.getNodeType() != Node.TEXT_NODE) {
            throw new RuntimeException("Element " + element.getTagName() + "does not have text content");
        }
        return textNode.getNodeValue();
    }
}