从Java中的Document获取xml字符串

And*_*dry 7 java xml

我有一个Java程序,旨在考虑一个xml dom并将其写入一个字符串.我正在使用这些包:org.w3c.dom.*javax.xml.parsers.*;

所以我有DocumentBuilder,Document,Element对象...

有没有办法在一次调用中获取代表我的xml dom的字符串????

Gra*_*min 17

它不是一个电话,而是:

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();
Run Code Online (Sandbox Code Playgroud)

setOutputProperty方法使字符串输出更漂亮,因此您可以将其取出.