jmurty/java-xmlbuilder

builder.asString(outputProperties) on existing XML file adds additional newline

hegdemk2004 opened this issue · 3 comments

Hi, Thanks for a simple framework ad beginner can also use. I followed the example provided in the Readme and found a minor issue. After creating the Projects.xml, Reading it back and Adding additional element , I wanted to write the updated XML back to file with proper indentation as before.

However the builder.asString(outputProperties) after the update, adds additional blank lines between each line of XML I think if I read, update and write (with outputProerties) an XML file multiple times, each time it will add additional blank lines. Is there a quick fix or workaround for this issue please? Thanks.

Hi @hegdemk2004 can you share your code where you are seeing this problem with excess whitespace?

I haven't been able to reproduce the issue myself with code like the following that writes and re-reads the same XML content to three files. My second and third files don't have extra blank lines.

Properties outputProperties = new Properties();
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");

XMLBuilder2 builder = XMLBuilder2.parse(EXAMPLE_XML_DOC);
builder.element("NewElement1");
File out1 = new File("/tmp/out1.xml");
builder.toWriter(new FileWriter(out1), outputProperties);

builder = XMLBuilder2.parse(out1);
builder.element("NewElement2");
File out2 = new File("/tmp/out2.xml");
builder.toWriter(new FileWriter(out2), outputProperties);

builder = XMLBuilder2.parse(out2);
builder.element("NewElement3");
File out3 = new File("/tmp/out3.xml");
builder.toWriter(new FileWriter(out3), outputProperties);

Hi, I still cannot reproduce the issue as described in MacOS. Perhaps there is some difference in our systems that prevents the extra whitespace for me but not you?

In any case, it sounds like you have found a solution to remove the newlines. The builder objects also have a method for doing this kind of clean-up, the stripWhitespaceOnlyTextNodes() method removes text nodes that contain nothing but whitespace.