XML 文档到字符串
获取 XML 文档 (org.w3c.dom.Document
) 的字符串表示形式的最简单方法是什么?也就是说,所有节点都将位于一条线上。
作为一个例子,从
<root>
<a>trge</a>
<b>156</b>
</root>
(这只是一个树表示,在我的代码中它是一个 org.w3c.dom.Document 对象,所以我不能将它视为字符串)
感谢
"<root> <a>trge</a> <b>156</b> </root>"
!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设
doc
是您的org.w3c.dom.Document
实例:Assuming
doc
is your instance oforg.w3c.dom.Document
:使用 Apache XMLSerializer
下面是一个示例:
http://www.informit.com/articles /article.asp?p=31349&seqNum=3&rl=1
你也可以检查这个
http://www.netomatix.com/XmlFileToString.aspx
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
首先,您需要删除所有文本节点中的所有换行符。然后你可以使用恒等变换来输出你的 DOM 树。查看 TransformerFactory#newTransformer() 的 javadoc。
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()
.