星期五, 二月 20, 2004

Transform a dom object to String/转换DOM对象为字符串

目的:把一个XML通过XSLT转换后的结果作为字符串返回.

Java Technology Forums: "transform a dom object to String? "
based on abhishek_srivastava code, here's a simple toString() method:

/**
* Prints a textual representation of a DOM object into a text string..
*
* @param document DOM object to parse.
* @return String representation of document.
*/
public static String document2String(Document document) {
String result = null;

StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try {
Transformer trans = tfac.newTransformer();
trans.transform(new DOMSource(document.getDocumentElement()), strResult);
} catch (Exception e) {
System.err.println("XMLUtils.document2String(): " + e);
}
result = strResult.getWriter().toString();

return result;
}//document2String()