Java 怎么允许编辑XML文件中的元素

2019年7月26日23:11:18Java 怎么允许编辑XML文件中的元素已关闭评论 415 1836字阅读6分7秒

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 void setElementContent(String filename, String name,
            String value) throws Exception {
        LOGGER.info("Editing the xml file " + filename);

        Document doc = parseDocument(filename);
        Node node = getNode(doc, name);
        if (node != null) {
            node.setNodeValue(value);

            
            LOGGER.info("Injecting data in the xml file");
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            StreamResult streamResult = new StreamResult(new File(filename));
            transformer.transform(domSource, streamResult);
        } else {
            LOGGER.warn("No XML element found with the given name " + name);
        }
    }
    
    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;
    }
}

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