3

I'm trying to simply add some blank lines to my jdom xml output. I've tried the following without luck:

Element root = new Element("root");
root.addContent(new CDATA("\n"));
root.addContent(new Text("\n"));

I figured the all-whitespace entry was being ignored so I tried creating my own XMLOutputProccessor like this:

class TweakedOutputProcessor extends AbstractXMLOutputProcessor {
    @Override
    public void process(java.io.Writer out, Format format, Text text) throws IOException {
        if ("\n".equals(text.getText())) {
            out.write("\n");
        } else {
            super.process(out, format, text);
        }
    }
}\

... called like this:

public static void printDocument(Document doc) {
    XMLOutputter xmlOutput = new XMLOutputter(new TweakedOutputProcessor());
    xmlOutput.setFormat(Format.getPrettyFormat());
    try {
            xmlOutput.output(doc, System.out);
    } catch (IOException e) { }
}

The unexpected thing here was that process(..., Text) was never called. After some experimentation I've found that process(..., Document) is being called, but none of the other process(..., *) methods are.

I also tried overriding the printText(...) and printCDATA(...) methods, but neither is being called -- even when the text is non-whitespace! Yet printElement(...) is being called.

So...

  • What is going on here? What's doing the work if not these methods?
  • How do I simply insert a blank line?
Didjit
  • 785
  • 2
  • 8
  • 26

1 Answers1

1

Use the XML xml:space="preserve" when setting values in the XML. JDOM honours that XML white space handling

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • 1
    Thanks @rolfl for the tip. So I tried `root.setAttribute("space", "preserve", Namespace.XML_NAMESPACE);`, which did indeed honor the blank lines, but it removed all Pretty-Printing formatting as well. Is there a way to get both? E.g. \n \t\n \t\n \n \t\n (does that make sense?) – Didjit Mar 07 '16 at 16:28