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 content of the first descendant of {@code ancestor} matching the specified
     * {@code tag}.
     * <p>
     * Example: let the {@link Element} {@code root} correspond to:
     *
     * <pre>
     * {@code <root>
     *     <name>
     *         <first>John</first>
     *         <last>Smith</last>
     *     </name>
     *     <last>BlahBlah</last>
     * </root>
     * 
     * getField(root, "last"); // returns "Smith"}
     * </pre>
     *
     * @param ancestor
     *            The starting point in the XML tree to look for descendants.
     * @param tag
     *            The tag of the desired descendant.
     * @return The content of the first descendant of {@code ancestor} matching the tag, or
     *         {@code null} if no such descendant exists.
     */
    public static String getField(Element ancestor, String tag) {
        NodeList children = ancestor.getElementsByTagName(tag);
        if (children.getLength() == 0) {
            return null;
        }
        return getContent(children.item(0));
    }

    /**
     * Returns the content of the specified node.
     * <p>
     * Example:
     *
     * <pre>
     * {@code <name>John</name>
     * 
     * getContent(name); // returns "John"}
     * </pre>
     *
     * @param node
     *            The node to get the field child from.
     * @return The content of the specified node, or {@code null} if no such content exists.
     */
    public static String getContent(Node node) {
        Node fieldNode = node.getFirstChild();
        if (fieldNode == null) {
            return null;
        }
        return fieldNode.getNodeValue();
    }
}