get Unique Element from Element by node name - Java XML

Java examples for XML:DOM Node Value

Description

get Unique Element 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 Element getUniqueElement(Element parent, String nodeName)
            throws XMLHelperException {
        return toElement(getUniqueNode(parent, nodeName));
    }/*w w  w.j  a va 2s. c  o m*/
    public static Element toElement(Node node) throws XMLHelperException {
        if (node.getNodeType() != Node.ELEMENT_NODE)
            throw new XMLHelperException("\"" + node.getNodeName()
                    + "\" must be an element node");
        return (Element) node;
    }
    public static Node getUniqueNode(Element parent, String nodeName)
            throws XMLHelperException {
        NodeList childNodes = parent.getChildNodes();
        int length = childNodes.getLength();

        Node node = null;
        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