[jdom-interest] setIndent("") doesn't work as expected

Laurent Bihanic laurent.bihanic at atosorigin.com
Wed Sep 6 16:18:37 PDT 2006


The problem comes from XMLOutputter itself:
     private void newline(Writer out) throws IOException {
         if (currentFormat.indent != null) {
             out.write(currentFormat.lineSeparator);
         }
     }
No indent, no newlines!

The easiest way to fix this is to create your own subclass of Format and 
override setIndent() to distinguish between "" and null.
Here's the current code:
     public Format setIndent(String indent) {
         // if passed the empty string, change it to null, for marginal
         // performance gains later (can compare to null first instead
         // of calling equals())
         if ("".equals(indent)) {
             indent = null;
         }
         this.indent = indent;
         return this;
     }
Remove the test on "" and XMLOutputter will behave as you expect.

Laurent

wkrick at eio-online.com a écrit :
> I'm currently outputting my document with the PrettyFormat...
> 
> Format fmt = Format.getPrettyFormat();
> fmt.setTextMode(Format.TextMode.PRESERVE);
> XMLOutputter outputter = new XMLOutputter(fmt);
> 
> ...and it works as expected, outputting one start/end tag per line.
> However, when I try to remove the indents on each line like this...
> 
> Format fmt = Format.getPrettyFormat();
> fmt.setTextMode(Format.TextMode.PRESERVE);
> fmt.setIndent("");
> XMLOutputter outputter = new XMLOutputter(fmt);
> 
> ...it removes all indents _AND_ newlines, compressing my whole document 
> into a single line of output.
> 
> I'm confused...
> 
> fmt.setIndent("  "); adds a two space indent
> fmt.setIndent(" "); adds a one space indent
> fmt.setIndent(""); no indent and removes newline on previous line?
> 
> I'm suspecting that the problem has something to do with...
> 
> fmt.setTextMode(Format.TextMode.PRESERVE);
> 
> ...but I need that mode to keep padding that's present in my document.
> 
> 
> Basically, given a document that looks like this...
> 
> <FOO><BAR>    12345</BAR><BAR>    67890</BAR></FOO>
> 
> ...I need the output to look like this...
> 
> <FOO>
> <BAR>    12345</BAR>
> <BAR>    67890</BAR>
> </FOO>
> 
> ...instead of this...
> 
> <FOO>
>   <BAR>    12345</BAR>
>   <BAR>    67890</BAR>
> </FOO>
> 
> ...but I can't seem to find the magic incantation that works.
> 
> Is this possible?


More information about the jdom-interest mailing list