Get child nodes as a string
Is it possible to get the child nodes under 开发者_StackOverflow中文版an XML element/node as a string in Java?
Or do you have iterate through everything?
Thanks
You can use Transformer:
private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException e) {
e.printStackTrace();
}
return sw.toString();
}
Yep, like Andrzej said, it depends on the library, For example, jDOM has the useful XMLOutputter
class that can print to streams, or as a String, or whatever. Most powerful XML libraries will have similar functionality
http://www.jdom.org/docs/apidocs/index.html
精彩评论