Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.*;

public class Main {
    /**
     * find element with tagName whose id tag is 'idTagName' and id value is 'id_value'
     *
     * @param root
     */
    public static Element findElement(final String idValue, final String idTagName, final String tagName,
            final Element root) {
        String textVal = null;
        final NodeList nl = root.getElementsByTagName(tagName);
        if (nl != null && nl.getLength() > 0) {
            // iterate over these
            for (int i = 0; i < nl.getLength(); i++) {
                final Element ei = (Element) nl.item(i);
                final NodeList n2 = ei.getElementsByTagName(idTagName);
                if (n2 != null && n2.getLength() > 0) {
                    for (int j = 0; j < n2.getLength(); j++) {
                        textVal = getElementValue((Element) n2.item(j));
                        if (textVal.equals(idValue)) {
                            return ei;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * find the unique element, returns null if not found or if there is more than one
     *
     * @param tagName - tag name
     * @param root    - where to start looking
     * @return the element
     */
    public static Element findElement(final String tagName, final Element root) {
        if (root.getTagName().equals(tagName)) {
            return root;
        }
        final NodeList nl = root.getElementsByTagName(tagName);
        if (nl != null && nl.getLength() == 1) {
            return (Element) nl.item(0);
        }
        return null;
    }

    /**
     * returns the text value associated with the element
     *
     * @param target - the element
     * @return - the text value
     */
    public static String getElementValue(final Element target) {

        final NodeList nodeList = target.getChildNodes();
        if (nodeList == null) {
            return null;
        }
        for (int current = 0; current < nodeList.getLength(); current++) {
            final Node node = nodeList.item(current);
            if (node instanceof Text) {
                final Text text = (Text) node;
                final String value = text.getNodeValue();
                if ((value != null) && (value.length() > 0)) {
                    return value;
                }
            }
        }
        return "";
    }
}