Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

xml - How to I output org.w3c.dom.Element to string format in java?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming you want to stick with the standard API...

You could use a DOMImplementationLS:

Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
    .getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...