如何将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);
但我需要将它存储在字符串变量中。
答案 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
中,我不记得了。