Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Element;

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

public class Main {
    /**
     * get the value of an Element in the Xml Document.
     * finds the first occurance of the parent element and then searches its children
     * for the first occurance of the element and retrieves its value.
     * @param root the root Element.
     * @param parent the name of the parent element to search for.
     * @param elemName the name of the child element to search for.
     * @return String the element value or null if not found.
     */
    public static String getSubElementValue(Element root, String parent, String elemName) {
        NodeList nl = root.getElementsByTagName(parent);
        String value = null;
        if (null == nl) {
            return (null);
        }
        Node node = nl.item(0);
        nl = node.getChildNodes();
        if (null == nl) {
            return (null);
        }

        boolean found = false;
        for (int i = 0; !found && i < nl.getLength(); ++i) {
            Node n = nl.item(i);
            if (elemName.equals(n.getNodeName())) {
                value = n.getFirstChild().getNodeValue().trim();
                found = true;
                break;
            } // if
        } // for
        return (value);
    }
}