1

我想知道如何使用 dom 解析器覆盖 Java 中的现有元素。例如,我有文件

我正在尝试覆盖元素并将其替换为元素

谢谢。

4

1 回答 1

2

算法很简单:

  1. 读取文件并将其解析为 XML 文档
  2. 进行任何您想要的更改
  3. 用新内容覆盖现有文件

看我的例子:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DomProgram {

    public static void main(String[] args) throws Exception {
        File xmlFile = new File("C:\\test.xml");

        Document document = readXmlDocument(xmlFile);

        makeChanges(document);

        Transformer transformer = createXmlTransformer();
        overwriteXmlFile(xmlFile, document, transformer);
    }

    private static void overwriteXmlFile(File xmlFile, Document document,
            Transformer transformer) throws FileNotFoundException,
            TransformerException {
        StreamResult result = new StreamResult(new PrintWriter(
                new FileOutputStream(xmlFile, false)));
        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);
    }

    private static Transformer createXmlTransformer() throws Exception {
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        return transformer;
    }

    private static void makeChanges(Document document) {
        Element root = document.getDocumentElement();
        root.setAttribute("test", "testvalue");
    }

    private static Document readXmlDocument(File xmlFile) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(xmlFile);
        return document;
    }
}

示例 XML 文件:

<note>
   <to>Ebele</to>
   <from>mykhaylo</from>
   <heading>Reminder</heading>
   <body>Read about problem before you ask ;)</body>
</note>

另见:

于 2013-01-26T00:45:56.413 回答