如何将 XML Prolog 添加到现有 XML Java
How to add XML Prolog to existing XML Java
我有一组 XML 个文件,其中序言已被删除。为了进一步处理我现在需要以编程方式添加此序言的文件。我当前的代码如下,但它确实写了一个空 XML。有人可以帮忙吗?
try(InputStream is = new FileInputStream(FILENAME + filename)){
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
doc.appendChild(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"ISO-8859-1\""));
//print XML
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
FileOutputStream output =
new FileOutputStream("/Users/XXX/Documents/New/" + filename);
StreamResult result = new StreamResult(new File(output+filename));
transformer.transform(source, result);
}
你写的代码没问题,但是在将更新后的 xml 保存到新文件时出现小错误
new StreamResult(new File(output+filename))
这里你将 FileOutputStream
作为参数传递给 File()
其实你不需要这样做 new StreamResult(output)
就够了
完整代码:
FileOutputStream output = new FileOutputStream("/Users/XXX/Documents/New/" + filename)
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
注:
Your code created xml file with filename like this java.io.FileOutputStream@3d82c5f3<filename>
in classpath
我有一组 XML 个文件,其中序言已被删除。为了进一步处理我现在需要以编程方式添加此序言的文件。我当前的代码如下,但它确实写了一个空 XML。有人可以帮忙吗?
try(InputStream is = new FileInputStream(FILENAME + filename)){
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
doc.appendChild(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"ISO-8859-1\""));
//print XML
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
FileOutputStream output =
new FileOutputStream("/Users/XXX/Documents/New/" + filename);
StreamResult result = new StreamResult(new File(output+filename));
transformer.transform(source, result);
}
你写的代码没问题,但是在将更新后的 xml 保存到新文件时出现小错误
new StreamResult(new File(output+filename))
这里你将 FileOutputStream
作为参数传递给 File()
其实你不需要这样做 new StreamResult(output)
就够了
完整代码:
FileOutputStream output = new FileOutputStream("/Users/XXX/Documents/New/" + filename)
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
注:
Your code created xml file with filename like this
java.io.FileOutputStream@3d82c5f3<filename>
in classpath