XML Node Simple value finder - Java XML

Java examples for XML:XML Node

Description

XML Node Simple value finder

Demo Code


//package com.java2s;

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

public class Main {
    /**// w  ww . jav a2s  .c  om
     * Simple value finder
     *
     * @param fromnode node from when we start deep search
     * @param name the node name
     * @return the value of the first matching node or null
     */
    protected static String findFirstValue(Node fromnode, String name) {
        Node node = findFirst(fromnode, name);
        return (node == null) ? null : node.getFirstChild().getNodeValue()
                .trim();
    }

    /**
     * Simple value finder
     *
     * @param fromnode node from when we start deep search
     * @param name the node name
     * @return the value of the first matching node or null
     */
    protected static Element findFirst(Node fromnode, String name) {
        NodeList nodelist = fromnode.getChildNodes();
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (name.equals(node.getNodeName())) {
                    return (Element) node;
                }
                Element el = findFirst(node, name);
                if (el != null) {
                    return el;
                }
            }
        }
        return null;
    }
}

Related Tutorials