Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.*;

public class Main {
    /** Helper method - gets a named element's value as a <I>long</I>.
       @param pElement The parent <I>Element</I>.
       @param strName Name of the element.
       @return Value of the element.
     */
    public static long getElementLong(Element pElement, String strName)
            throws ClassCastException, NumberFormatException {
        String strValue = getElementString(pElement, strName);

        if (null == strValue)
            return Long.MIN_VALUE;

        return Long.parseLong(strValue);
    }

    /** Helper method - gets a named element's value as a <I>String</I>.
       @param pElement The parent <I>Element</I>.
       @param strName Name of the element.
       @return Value of the element.
     */
    public static String getElementString(Element pElement, String strName) throws ClassCastException {
        Node pNodeValue = findNode(pElement, strName);

        if (null == pNodeValue)
            return null;

        return getNodeText(pNodeValue);
    }

    /** Helper method - finds the node with the specified element name. The returned node can be
    the passed in node itself or one of its child nodes. The first node found is the
    one returned.
       @param pNode A <I>org.w3c.dom.Node</I> object being searched.
       @param strElementName Name of the element being searched for.
       @return <I>org.w3c.dom.Node</I> object.
     */
    public static Node findNode(Node pNode, String strElementName) {
        // Check the parent, first.
        if (pNode.getNodeName().equals(strElementName))
            return pNode;

        NodeList pNodeList = null;

        if (pNode instanceof Element)
            pNodeList = ((Element) pNode).getElementsByTagName(strElementName);

        else if (pNode instanceof Document)
            pNodeList = ((Document) pNode).getElementsByTagName(strElementName);

        if ((null == pNodeList) || (0 == pNodeList.getLength()))
            return null;

        return pNodeList.item(0);
    }

    /** Helper method - gets the text value of an element node. The text value
    is stored in the child nodes.
       @param pNode A org.w3c.dom.Node object.
       @return Element's text.
     */
    public static String getNodeText(Node pNode) {
        NodeList pChildren = pNode.getChildNodes();
        int nLength = pChildren.getLength();

        if (0 == nLength)
            return null;

        String strReturn = "";

        for (int i = 0; i < nLength; i++) {
            Node pChild = pChildren.item(i);

            if (pChild instanceof CharacterData)
                strReturn += ((CharacterData) pChild).getData();
        }

        if (0 == strReturn.length())
            return null;

        return strReturn;
    }
}