Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert blank lines in jdom2 pretty printing

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?
like image 520
Didjit Avatar asked Dec 31 '25 06:12

Didjit


1 Answers

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

like image 76
rolfl Avatar answered Jan 04 '26 13:01

rolfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!