本文介绍了XML 文档到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取 XML 文档 (org.w3c.dom.Document) 的字符串表示形式的最简单方法是什么?也就是说,所有节点都在一行上.

What's the simplest way to get the String representation of a XML Document (org.w3c.dom.Document)? That is all nodes will be on a single line.

举个例子,来自

<root>
  <a>trge</a>
  <b>156</b>
</root>

(这只是一个树表示,在我的代码中它是一个 org.w3c.dom.Document 对象,所以我不能把它当作一个字符串)

(this is only a tree representation, in my code it's a org.w3c.dom.Document object, so I can't treat it as a String)

"<root> <a>trge</a> <b>156</b> </root>"

谢谢!

推荐答案

假设 doc 是您的 org.w3c.dom.Document 实例:

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("
|
", "");

这篇关于XML 文档到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:43