Java 怎么查找并返回最后一个子XML元素节点

2019年8月6日22:16:51Java 怎么查找并返回最后一个子XML元素节点已关闭评论 682 1419字阅读4分43秒

1.简介

Java 怎么查找并返回最后一个子XML元素节点?——请看下文。

2.示例代码

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

 


import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    
    public static Element getLastChildElement(Node parent) {

        
        Node child = parent.getLastChild();
        while (child != null) {
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                return (Element) child;
            }
            child = child.getPreviousSibling();
        }

        
        return null;

    }

    
    public static Element getLastChildElement(Node parent, String elemName) {

        
        Node child = parent.getLastChild();
        while (child != null) {
            if (child.getNodeType() == Node.ELEMENT_NODE
                    && child.getLocalName().equals(elemName)) {
                return (Element) child;
            }
            child = child.getPreviousSibling();
        }

        
        return null;

    }

    
    public static Element getLastChildElement(Node parent,
            String elemNames[]) {

        
        Node child = parent.getLastChild();
        while (child != null) {
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                for (String elemName : elemNames) {
                    if (child.getLocalName().equals(elemName)) {
                        return (Element) child;
                    }
                }
            }
            child = child.getPreviousSibling();
        }

        
        return null;

    }

    
    public static Element getLastChildElement(Node parent, String elemName,
            String attrName, String attrValue) {

        
        Node child = parent.getLastChild();
        while (child != null) {
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) child;
                if (element.getLocalName().equals(elemName)
                        && element.getAttribute(attrName).equals(attrValue)) {
                    return element;
                }
            }
            child = child.getPreviousSibling();
        }

        
        return null;

    }

    
    public static String getLocalName(Node node) {
        String name = node.getLocalName();
        return name != null ? name : node.getLocalName();
    }
}

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