gpt4 book ai didi

java - dom 文档到字符串

转载 作者:行者123 更新时间:2023-12-02 08:36:39 25 4
gpt4 key购买 nike

我在java中有一个方法,它有2个字符串参数,它将字符串写入文件,现在我有dom文档,它保存我需要写入文件的值,但它不是字符串类型,我如何将它转换为这里的字符串是我的代码:

import java.io.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

public static boolean saveStringToFile(String fileName, String saveString)
{
boolean saved = false;
BufferedWriter bw = null;

try {
bw = new BufferedWriter(new FileWriter(fileName));

try {
bw.write(saveString);
saved = true;
}
finally {
bw.close();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
return saved;
}

static public void main(String[] arg) {
try{
String xmlFile = "Management.xml";
File file = new File(xmlFile);
String remElement = "Physical_Order_List_Array";
if (file.exists()){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer tFormer = tFactory.newTransformer();
Element element = (Element)doc.getElementsByTagName(remElement).item(0);
// Remove the node
element.getParentNode().removeChild(element);
// Normalize the DOM tree to combine all adjacent nodes
doc.normalize();
Source source = new DOMSource(doc);
Result dest = new StreamResult(System.out);
tFormer.transform(source, dest);
// System.out.println();
// saveStringToFile("emir.xml", "dsds"); -> write method
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
System.err.println(e);
System.exit(0);
}
}
}

最佳答案

为什么要将其转换为String?只是为了稍后将其写入文件吗?为什么不只做

 Result dest = new StreamResult(new FileOutputStream("foo.xml"));

如果您需要字符串:

StringWriter w = new StringWriter();
Result dest = new StreamResult(w);
tFormer.transform(source, dest);
String xmlString = w.toString();

关于java - dom 文档到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1566701/

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