XML Document to String

≡放荡痞女 提交于 2019-11-26 07:25:47

问题


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!


回答1:


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", "");



回答2:


Use the Apache XMLSerializer

here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1

you can check this as well

http://www.netomatix.com/XmlFileToString.aspx




回答3:


First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().



来源:https://stackoverflow.com/questions/5456680/xml-document-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!