get Unique Node from Element by node name - Java XML

Java examples for XML:DOM Node Value

Description

get Unique Node from Element by node name

Demo Code


import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    public static Node getUniqueNode(Element parent, String nodeName)
            throws XMLHelperException {
        NodeList childNodes = parent.getChildNodes();
        int length = childNodes.getLength();

        Node node = null;/*from  w w  w .j av  a2  s . c o  m*/
        for (int i = 0; i < length; i++) {
            Node current = childNodes.item(i);
            if (current.getNodeName().equals(nodeName)) {
                if (node != null)
                    throw new XMLHelperException("\"" + nodeName
                            + "\" in \"" + parent.getNodeName()
                            + "\" must be unique");
                node = current;
            }
        }

        if (node == null)
            throw new XMLHelperException("\"" + nodeName
                    + "\" not found in \"" + parent.getNodeName() + "\"");
        return node;
    }
}

Related Tutorials