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

问题描述

获取XML文档的String表示的最简单方法是什么( org.w3c.dom.Document )?所有节点都将在一行上。



例如,从

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

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



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

谢谢!

解决方案

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

  TransformerFactory tf = TransformerFactory.newInstance(); 
变压器变压器= tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,yes);
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc),新的StreamResult(writer));
String output = writer.getBuffer()。toString()。replaceAll(\\\
| \r,);


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.

As an example, from

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

(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)

to

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

Thanks!

解决方案

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("\n|\r", "");

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

10-28 05:43