get XML Node Attribute Deep - Java XML

Java examples for XML:XML Attribute

Description

get XML Node Attribute Deep

Demo Code


//package com.java2s;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static String getNodeAttributeDeep(NodeList nodelList,
            String nodeName, String nodeAttr) {
        for (int i = 0; i < nodelList.getLength(); i++) {
            Node node = nodelList.item(i);
            if (node.getNodeName().equals(nodeName)) {
                return getNodeAttribute(node, nodeAttr);
            }//from   w  ww .j  a  v a2s .  c  om
            if (node.getChildNodes().getLength() > 0) {
                String result = getNodeAttributeDeep(node.getChildNodes(),
                        nodeName, nodeAttr);
                if (result != null)
                    return result;
            }
        }
        return null;
    }

    public static String getNodeAttribute(Node node, String s) {
        NamedNodeMap attributes = node.getAttributes();
        for (int k = 0; k < attributes.getLength(); k++) {
            Node nodeAttr = attributes.item(k);
            if (nodeAttr.getNodeName().equals(s)) {
                return nodeAttr.getNodeValue();
            }
        }
        return null;
    }
}

Related Tutorials