I would like my XML to be not-pretty printed, i.e. all on one line, no spaces between elements. e.g.
<element>value</element><element><nested>value</nested></element>
(Exception handling removed)
public String transform(Document doc) {
javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
DOMSource source = new DOMSource(doc);
transformer.transform(source, new StreamResult(stringWriter));
String result = stringWriter.toString();
return result;
}
Even with OutputKeys.INDENT
as no
, I am still getting pretty-printed XML when my input is created from pretty-printed XML.
I looked at How to unformat xml file, but I cannot just strip newlines and whitespaces from my XML, as my data may contain them. I don't really want to parse the string and format it myself, but I can't think of any other solution.
I am being passed the Document
object, so I cannot modify the DocumentBuilder (as seen here https://stackoverflow.com/a/15462951/3887715). I could use the StringBuilder solution (https://stackoverflow.com/a/13163891/3887715), but I am concerned that any comments will be merged if they span multiple lines.
However, this is mostly used for logging purposes, so lacking any other solution, I think the StringBuilder one is the cleanest.