Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    /**
     * 
     * 
     * @param node
     *            Node object
     * @param childName
     *            Name of child node looking for
     * @param createNode
     *            If true, appends a child node with given name when not found
     * @return Node Child Node
     * @throws IllegalArgumentException
     *             for Invalid input
     */
    public static Node getChildNodeByName(final Node node, final String childName, final boolean createNode)
            throws IllegalArgumentException {
        // Validate node
        if (node == null) {
            throw new IllegalArgumentException("Node cannot " + "be null in XmlUtils.getChildNodebyName method");
        }

        // Validate child name
        if (childName == null) {
            throw new IllegalArgumentException(
                    "Child name cannot" + " be null in XmlUtils.getChildNodebyName method");
        }

        final NodeList childList = node.getChildNodes();
        if (childList != null) {
            for (int childIndex = 0; childIndex < childList.getLength(); childIndex++) {
                if (childName.equals(childList.item(childIndex).getNodeName())) {
                    return childList.item(childIndex);
                }
            }
        }

        if (createNode) {
            final Node newNode = node.getOwnerDocument().createElement(childName);
            node.appendChild(newNode);
            return newNode;
        } else {
            return null;
        }
    }

    /***
     * Get the name of the node without namespace
     * 
     * @param node
     * @return
     */
    public static String getNodeName(final Node node) {

        if (node == null) {
            return null;
        }

        String nodeName = node.getNodeName();

        // Remove namespace prefix if present
        int indexOfColon;
        if ((nodeName != null) && (nodeName.length() > 0 // Node name is not
        // empty
        ) && ((indexOfColon = nodeName.indexOf(':')) >= 0)
        // there is a colon in the nodename
                && (indexOfColon < (nodeName.length() - 1))
        // colon is not at the end of the name
        ) {
            nodeName = nodeName.substring(nodeName.indexOf(':') + 1);
        }

        return nodeName;
    }
}