有没有比此代码更优雅的方法将 XML 文档转换为 Java 中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/315517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a more elegant way to convert an XML Document to a String in Java than this code?
提问by Brian
Here is the code currently used.
这是当前使用的代码。
public String getStringFromDoc(org.w3c.dom.Document doc) {
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
writer.flush();
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
采纳答案by ykaganovich
Relies on DOM Level3 Load/Save:
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
return lsSerializer.writeToString(doc);
}
回答by Fernando Miguélez
The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN Java XML API for XML Processing.
转换器 API 是将 DOM 对象转换为序列化形式(在本例中为 String)的唯一 XML 标准方式。作为标准,我指的是 SUN Java XML API for XML Processing。
Other alternatives such as Xerces XMLSerializeror JDOM XMLOutputterare more direct methods (less code) but they are framework-specific.
其他替代方案,如 Xerces XMLSerializer或 JDOM XMLOutputter是更直接的方法(更少的代码),但它们是特定于框架的。
In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?
在我看来,您使用的方式是最优雅、最便携的。通过使用标准的 XML Java API,您可以插入您选择的 XML-Parser 或 XML-Transformer,而无需更改代码(与 JDBC 驱动程序相同)。还有比这更优雅的吗?
回答by digitalsanctum
This is a little more concise:
这更简洁一点:
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
return result.getWriter().toString();
} catch(TransformerException ex) {
ex.printStackTrace();
return null;
}
Otherwise you could use a library like XMLSerializer from Apache:
否则,您可以使用 Apache 中的 XMLSerializer 之类的库:
//Serialize DOM
OutputFormat format = new OutputFormat (doc);
// as a String
StringWriter stringOut = new StringWriter ();
XMLSerializer serial = new XMLSerializer (stringOut,format);
serial.serialize(doc);
// Display the XML
System.out.println(stringOut.toString());