如何在java中将org.w3c.dom.Element输出为字符串格式? [英] How to I output org.w3c.dom.Element to string format in java?
问题描述
我有一个 org.w3c.dom.Element
对象传递到我的方法中.我需要查看整个 xml 字符串,包括其子节点(整个对象图).我正在寻找一种可以将 Element
转换为我可以 System.out.println
的 xml 格式字符串的方法.'Element' 对象上的 println()
将不起作用,因为 toString()
不会输出 xml 格式,也不会通过其子节点.有没有一种简单的方法而不编写我自己的方法来做到这一点?谢谢.
I have an org.w3c.dom.Element
object passed into my method. I need to see the whole xml string including its child nodes (the whole object graph). I am looking for a method that can convert the Element
into an xml format string that I can System.out.println
on. Just println()
on the 'Element' object won't work because toString()
won't output the xml format and won't go through its child node. Is there an easy way without writing my own method to do that? Thanks.
推荐答案
假设您想坚持使用标准 API...
Assuming you want to stick with the standard API...
您可以使用 DOMImplementationLS:
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);
如果 <?xml version="1.0" encoding="UTF-16"?>声明打扰你,你可以使用 变压器 代替:
If the <?xml version="1.0" encoding="UTF-16"?> declaration bothers you, you could use a transformer instead:
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node),
new StreamResult(buffer));
String str = buffer.toString();
这篇关于如何在java中将org.w3c.dom.Element输出为字符串格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!