簡體   English   中英

用Java將XML文檔寫入文件的最佳方法是哪種?

[英]Which is the best way to write a XML Document to a file in java?

我正在嘗試編寫XML文件。 我可以使用以下代碼創建文檔。 我想將此文檔寫入具有縮進支持的文件中。 目前,我的代碼如下所示。

這是解析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();    
}

兩種方法有什么區別? 哪些技術可以提供更好的性能?

為了回答您的問題,我建議第三種方法是W3C建議的DOM Load and Save 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或多或少是一種預標准不同,該方法是首選方法,因為所有兼容的實現均支持該方法。 但是,性能很大程度上取決於供應商的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM