Java 怎么返回具有给定名称的XML节点的文本内容

2019年8月3日23:42:21Java 怎么返回具有给定名称的XML节点的文本内容已关闭评论 322 1431字阅读4分46秒

1.简介

Java 怎么返回具有给定名称的XML节点的文本内容?——请看下文。

2.示例代码

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

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    
    private final static Logger LOGGER = Logger
            .getLogger(Constants.CUKES_TESTS_LOGGER);
    private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory
            .newInstance();
    
    public static String getElementContent(String filename, String name)
            throws Exception {
        Document doc = parseDocument(filename);
        Node node = getNode(doc, name);
        if (node != null) {
            return node.getTextContent();
        }
        return null;

    }
    
    private static Document parseDocument(String filename) throws Exception {
        LOGGER.info("Loading the xml file " + filename);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        LOGGER.info("parse the content of the file");
        return dBuilder.parse(new File(filename));
    }
    
    private static Node getNode(Document doc, String name) throws Exception {
        NodeList list = doc.getDocumentElement().getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            
            if (node.getNodeType() == Node.ELEMENT_NODE
                    && name.equals(node.getNodeName())) {
                Node data = node.getChildNodes().item(0);
                if (data.getNodeType() == Node.TEXT_NODE) {
                    return data;
                }
            }
        }
        return null;
    }
}

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