从DOM获取XML字符串

时间:2013-12-22 17:10:48

标签: java xml dom

如何将DOM解析器生成的XML存储在Java中的字符串变量中?我可以使用:

将其存储在.xml文件中
// creating and writing to xml file  
TransformerFactory transformerFactory = TransformerFactory.newInstance();  
Transformer transformer = transformerFactory.newTransformer();  
DOMSource domSource = new DOMSource(document);  
StreamResult streamResult = new StreamResult(new File("d:/xml_created.xml"));
transformer.transform(domSource, streamResult);

但我需要将它存储在字符串变量中。

1 个答案:

答案 0 :(得分:2)

您可以创建StringWriter并将XML打印到:

http://docs.oracle.com/javase/7/docs/api/java/io/StringWriter.html

StringWriter sw = new StringWriter();

transformer.transform(domSource, sw);

String xml = sw.toString();

您可能需要将StringWriter包裹在OutputStream中,我不记得了。