gpt4 book ai didi

java - 使用 dom 解析器 api 在 Java 中覆盖现有 XML 文档

转载 作者:行者123 更新时间:2023-11-30 04:31:36 25 4
gpt4 key购买 nike

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

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

谢谢。

最佳答案

算法很简单:

  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>

另请参阅:

关于java - 使用 dom 解析器 api 在 Java 中覆盖现有 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14532167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com