gpt4 book ai didi

java - 将 XML 格式保存为字符串而不是文件

转载 作者:行者123 更新时间:2023-11-30 03:00:19 26 4
gpt4 key购买 nike

我使用 DocumentBuilderFactory 创建 XML 文件,如下所示:How to create XML file with specific structure in Java

我想将结果存储为 java 字符串,而不是将其保存到文件中。如何实现这一目标。

重复: How do I convert a org.w3c.dom.Document object to a String?

最佳答案

这个例子可能会帮助你。

import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 DOMBasicDoc {
public static void main(String args[]) {
try {
String[] input = {"John Doe,123-456-7890", "Bob Smith,123-555-1212"};
String[] line = new String[2];
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
Element root = doc.createElement("root");
doc.appendChild(root);
Element memberList = doc.createElement("members");
root.appendChild(memberList);
for (int i = 0; i < input.length; i++) {
line = input[i].split(",");
Element member = doc.createElement("member");
memberList.appendChild(member);
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode(line[0]));
member.appendChild(name);
Element phone = doc.createElement("phone");
phone.appendChild(doc.createTextNode(line[1]));
member.appendChild(phone);
}
TransformerFactory tFact = TransformerFactory.newInstance();
Transformer trans = tFact.newTransformer();

StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
System.out.println(writer.toString());

} catch (TransformerException ex) {
System.out.println("Error outputting document");
} catch (ParserConfigurationException ex) {
System.out.println("Error building document");
}
}
}

关于java - 将 XML 格式保存为字符串而不是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36174793/

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