Find XML Element by node, attribute name and attribute value - Java XML

Java examples for XML:XML Attribute

Description

Find XML Element by node, attribute name and attribute value

Demo Code


//package com.java2s;

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

public class Main {

    public static Element findElement(Node sourceElm, String attrName,
            String sAttrValue) {//from ww  w. j  a  v a  2 s.c o  m
        if (sourceElm.hasChildNodes()) {
            NodeList nodes = sourceElm.getChildNodes();

            for (int i = 0; i < nodes.getLength(); i++) {
                if (Node.ELEMENT_NODE == nodes.item(i).getNodeType()) {
                    Element elm = findElement(nodes.item(i), attrName,
                            sAttrValue);

                    if (((Element) elm).getAttribute(attrName).equals(
                            sAttrValue)) {
                        return (Element) elm;
                    }
                }
            }
        } else {
            if (sourceElm.hasAttributes()
                    && ((Element) sourceElm).getAttribute(attrName).equals(
                            sAttrValue)) {
                return (Element) sourceElm;
            }
        }

        return (Element) sourceElm;
    }
}

Related Tutorials