将xml doc转换为字符串结果为空字符串

时间:2018-05-23 12:32:19

标签: java xml dom javax

尝试使用javax.xml.transform.Transformer执行从dom.Document到String的简单解析,它会产生一个空字符串。

代码:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(sw);
transformer.transform(source, console);

调试结果:

的System.out.println(source.getNode()getFirstChild()getNodeName());

                     <root element is displayed>

System.out.println(&#34; DONE:&#34; + console.getWriter()。toString());

                      <Empty string is displayed>

请知道为什么我得到空字符串,而我需要获取转换后的xml字符串

  

块引用

0 个答案:

没有答案