Java 怎么返回具有给定名称的所有XML元素的串联

2019年7月26日23:10:43Java 怎么返回具有给定名称的所有XML元素的串联已关闭评论 387 1122字阅读3分44秒

1.简介

Java 怎么返回具有给定名称的所有XML元素的串联?——请看下文。

2.示例代码

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

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

public class Main{
    
    public static String getAllElementText(Element node, String name) {
        StringBuffer temp = new StringBuffer();
        NodeList list = node.getElementsByTagName(name);
        for (int j = 0; j < list.getLength(); j++) {
            temp.append(getSimpleElementText((Element) list.item(j)));
        }
        return temp.toString();
    }
    
    public static String getSimpleElementText(Element node, String name) {
        Element namedElement = getFirstElement(node, name);
        return getSimpleElementText(namedElement);
    }
    
    public static String getSimpleElementText(Element node) {
        StringBuffer sb = new StringBuffer();
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child instanceof Text)
                sb.append(child.getNodeValue());
        }
        return sb.toString();
    }
    
    public static Element getFirstElement(Element element, String name) {
        NodeList nl = element.getElementsByTagName(name);
        if (nl.getLength() < 1)
            throw new RuntimeException("Element: " + element
                    + "does not contain: " + name);
        return (Element) nl.item(0);
    }
}

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