如何在java中输出org.w3c.dom.Element到字符串格式? [英] How to I output org.w3c.dom.Element to string format in java?
问题描述
我有一个 org.w3c.dom.Element
对象传递到我的方法。我需要看到整个xml字符串,包括它的子节点(整个对象图)。我正在寻找一种方法,可以将元素
转换为一个xml格式的字符串,我可以 System.out.println
上。 元素对象上的 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.0encoding =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屋!