Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce WhiteSpace In PrettyPrint #147

Open
opticyclic opened this issue Aug 5, 2022 · 1 comment
Open

Reduce WhiteSpace In PrettyPrint #147

opticyclic opened this issue Aug 5, 2022 · 1 comment
Labels

Comments

@opticyclic
Copy link

OutputFormat.createPrettyPrint() adds extra space that I don't tend to see in xml.
It adds a space at the end of every line and a blank line after the declaration.
This goes away if you add the following after it:

format.setPadText(false);
format.setNewLineAfterDeclaration(false);

Whilst whitespace in these places is still valid xml, it feels like they shouldn't be the defaults.

A quick search doesn't show examples using this extra whitespace.
e.g.
https://docs.oracle.com/javase/tutorial/jaxp/stax/example.html#bnbfn
https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)

@unkarjedy
Copy link

Observed the same issue.
Example:

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class Main {
    private static final String xmlString = "<test>\n" +
            "  <one>1</one>\n" +
            "  <two>1</two>\n" +
            "</test>\n";

    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(xmlString));

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndentSize(2);
        format.setTrimText(true);
        format.setExpandEmptyElements(true);
        format.setNewLineAfterDeclaration(false);

        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);

        writer.write(document);
        System.out.println(stringWriter);
    }
}

outputs

<?xml version="1.0" encoding="UTF-8"?>
<test> 
  <one>1</one>  
  <two>1</two> 
</test>

(notice spaces in <one>1</one> and <two>1</two>
instead of

<?xml version="1.0" encoding="UTF-8"?>
<test>
  <one>1</one>
  <two>1</two>
</test>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

3 participants