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 {
    /***************************************************************************
     * Returns the value of the first child under the give element with the
     * given name.
     * 
     * @param e
     * @param name
     * @return
     * @throws Exception
     **************************************************************************/
    public static String getChildValueByName(Element e, String name) throws Exception {
        String s = "Not found";

        /*
         * The getElementsByTagName() function returns ANY children under the
         * given element with the given tag name. This function is intended to
         * return the value of only an immediate child with a given name.
         */
        NodeList childNodes = e.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            if (node.getNodeName().equals(name)) {
                if (node.getFirstChild() != null)
                    s = node.getFirstChild().getNodeValue();
                else
                    s = "";
                break;
            }
        }

        return s;
    }
}