我正在尝试编写一个XML文件。我能够使用以下代码创建Document。我想将此文档写入具有缩进支持的文件。目前我的代码看起来像这样。
哪种解析XMl并写入文件的技术更好。
public void writeXmlToFile(Document dom) throws IOException {
OutputFormat format = new OutputFormat(dom);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer ( new FileOutputStream(
new File("sample.xml")), format);
serializer.serialize(dom);
}
或正在使用变压器更好的方法。
public void writeXMLToFile(DOcument dom) throws TransformerException, IOException {
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer();
trans.setOutputProperty(OutputKeys.ENCODING, "utf-8");
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProeprty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult resut = new StreamResult(new FileWriter(output));
DOMSource source = new DOMSource(xmlDOC);
trans.transform(source, result);
writer.close();
}
这两种方法有什么区别?哪种技术可以提供更好的性能?
答案 0 :(得分:0)
为了回答你的问题,我建议第三种方法是W3C提出的DOM加载和保存API。代码是自我解释的。
DOMImplementationLS ls = (DOMImplementationLS)
DOMImplementationRegistry.newInstance().getDOMImplementation("LS");
// Gets a basic document from string.
LSInput input = ls.createLSInput();
String xml = "<bookstore city='shanghai'><a></a><b/></bookstore>";
InputStream istream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
input.setByteStream(istream);
LSParser parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
Document document = parser.parse(input);
// Creates a LSSerializer object and saves to file.
LSSerializer serializer = ls.createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", true);
LSOutput output = ls.createLSOutput();
OutputStream ostream = new FileOutputStream("c:\\temp\\foo.xml");
output.setByteStream(ostream);
serializer.write(document, output);
与XmlSerializer或多或少是预标准不同,这种方法是首选,因为所有兼容的实现都支持这种方法。但性能在很大程度上取决于供应商的实施。