Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

XML Node to String in Java

I came across this piece of Java function to convert an XML node to a Java String representation:

private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
 Transformer t = TransformerFactory.newInstance().newTransformer();
 t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 t.setOutputProperty(OutputKeys.INDENT, "yes");
 t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
 System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}

It looks straightforward in that it wants the output string doesn't have any XML declaration and it must contain indentation.

But I wonder how the actual output should be, suppose I have an XML node:

<p><media type="audio" id="au008093" rights="wbowned">
<title>Bee buzz</title>
</media>Most other kinds of bees live alone instead of in a colony. These bees make
        tunnels in wood or in the ground. The queen makes her own nest.</p>

Could I assume the resulting String after applying the above transformation is:

"media type="audio" id="au008093" rights="wbowned" title Bee buzz title /media"

I want to test it myself, but I have no idea on how to represent this XML node in the way this function actually wants.

I am bit confused, and thanks in advance for the generous help.

question from:https://stackoverflow.com/questions/4412848/xml-node-to-string-in-java

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

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...