I have xml-file. I need to read it, make some changes and write new changed version to some new destination.
我有xml文件。我需要阅读它,进行一些更改并将新的更改版本写入一些新目的地。
I managed to read, parse and patch this file (with DocumentBuilderFactory
, DocumentBuilder
, Document
and so on).
我设法读取,解析和修补此文件(使用DocumentBuilderFactory,DocumentBuilder,Document等)。
But I cannot find a way how to save that file. Is there a way to get it's plain text view (as String
) or any better way?
但我找不到如何保存该文件的方法。有没有办法让它的纯文本视图(如String)或更好的方式?
3 个解决方案
#1
63
Something like this works:
像这样的东西有效:
Transformer transformer = TransformerFactory.newInstance().newTransformer();Result output = new StreamResult(new File("output.xml"));Source input = new DOMSource(myDocument);transformer.transform(input, output);
#2
2
That will work, provided you're using xerces-j:
如果您使用的是xerces-j,那将会有效:
public void serialise(org.w3c.dom.Document document) { java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream(); java.io.PrintStream ps = new java.io.PrintStream(data); org.apache.xml.serialize.OutputFormat of = new org.apache.xml.serialize.OutputFormat("XML", "ISO-8859-1", true); of.setIndent(1); of.setIndenting(true); org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer(ps, of); // As a DOM Serializer serializer.asDOMSerializer(); serializer.serialize(document); return data.toString();}
#3
0
That will give you possibility to define xml format
这将为您提供定义xml格式的可能性
new XMLWriter(new FileOutputStream(fileName), new OutputFormat(){{ setEncoding("UTF-8"); setIndent(" "); setTrimText(false); setNewlines(true); setPadText(true); }}).write(document);
#1
63
Something like this works:
像这样的东西有效:
Transformer transformer = TransformerFactory.newInstance().newTransformer();Result output = new StreamResult(new File("output.xml"));Source input = new DOMSource(myDocument);transformer.transform(input, output);
#2
2
That will work, provided you're using xerces-j:
如果您使用的是xerces-j,那将会有效:
public void serialise(org.w3c.dom.Document document) { java.io.ByteArrayOutputStream data = new java.io.ByteArrayOutputStream(); java.io.PrintStream ps = new java.io.PrintStream(data); org.apache.xml.serialize.OutputFormat of = new org.apache.xml.serialize.OutputFormat("XML", "ISO-8859-1", true); of.setIndent(1); of.setIndenting(true); org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer(ps, of); // As a DOM Serializer serializer.asDOMSerializer(); serializer.serialize(document); return data.toString();}
#3
0
That will give you possibility to define xml format
这将为您提供定义xml格式的可能性
new XMLWriter(new FileOutputStream(fileName), new OutputFormat(){{ setEncoding("UTF-8"); setIndent(" "); setTrimText(false); setNewlines(true); setPadText(true); }}).write(document);