[英]Getting xml string from Document in Java
我有一個Java程序,旨在考慮一個xml dom並將其寫入一個字符串。 我正在使用這些包: org.w3c.dom.*
和javax.xml.parsers.*;
所以我有DocumentBuilder
, Document
, Element
對象......
有沒有辦法在一次調用中獲取代表我的xml dom的字符串????
它不是一個電話,而是:
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());
trans.transform(source, result);
String xmlString = sw.toString();
setOutputProperty方法使字符串輸出更漂亮,因此您可以將其取出。
String xmlString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
方法org.apache.axis.utils.XMLUtils.PrettyDocumentToString(Document)的問題包括標記值中的空格。
解決方案是使用方法org.apache.axis.utils.XMLUtils.DocumentToString(Document)。
我也在尋找一種廉價而有效的序列化DOM的方法。 到目前為止,我只看到兩個選項:
也許您可以嘗試LSSerializer方法(但不能在一次調用中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.