2

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.

Community
  • 1
  • 1
Fodder
  • 564
  • 1
  • 10
  • 23
  • 1
    Hehe, I thought you meant like "unsort" or "uglify". :) – Prof. Falken Oct 02 '14 at 07:05
  • Unfortunately, I am being passed the Document object, so I can't build it myself. If I use the StringBuilder solution, won't any comments in my XML be messed up if they span multiple lines (words at the end and beginning of lines will merge together)? – Fodder Oct 02 '14 at 07:15

0 Answers0