Reputation: 1350
I want to convert node to string, for that I am using following code snippet:
private static 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, "no");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
Log.e(TAG, "Node transformation exception " + te.getMessage());
}
return sw.toString();
}
The problem I am facing is that, it is removing space at the end of node.
<Message Text="OK" /> to <Message Text="OK"/>
Can anyone tell me how can I avoid trimming of space ? Any help would be appreciated.
Regards, Yuvi
Upvotes: 0
Views: 334
Reputation: 122364
Can anyone tell me how can I avoid trimming of space ?
Since <Message Text="OK" />
and <Message Text="OK"/>
are exactly the same XML it should make no difference to a proper XML parser.
If for some reason it does matter (e.g. you're feeding this output to a non-XML tool that can't cope without the space) then you could try the Saxon transformer implementation, which supports XSLT 2.0. XSLT 2.0 provides an "xhtml" output method which you could use instead of the default "xml", and which does serialization following the HTML compatibility guidelines of XHTML. Among other things this means it writes all empty tags either with a space (<br />
) or in "expanded" form (<example></example>
).
Upvotes: 2
Reputation: 24444
The DOM model does not provide a way to express extra whitespace within an XML tag. It has only information about the name of the tag, its attributes and their values.
From perspective of XML, the extra whitespace is not important - both representations are equal.
Upvotes: 1