Java 怎么按节点名称从元素中获取唯一元素

2019年7月23日22:48:59Java 怎么按节点名称从元素中获取唯一元素已关闭评论 337 1055字阅读3分31秒

1.简介

Java 怎么按节点名称从元素中获取唯一元素?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

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));
    }
    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;
    }
}

 
继续阅读
编程十万个怎么办