Skip to content

Rough idea on how to preserve newlines #31

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

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Rough idea on how to preserve newlines
  • Loading branch information
aaime committed Mar 22, 2021
commit 758f48ef7f559e20d62af5e31631dd4d571fa52d
50 changes: 49 additions & 1 deletion src/main/java/au/com/acegi/xmlformat/FormatUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.StringTokenizer;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
Expand Down Expand Up @@ -78,7 +81,52 @@ public InputSource resolveEntity(final String publicId,
});
final Document xmlDoc = reader.read(in);

final XMLWriter xmlWriter = new XMLWriter(out, fmt);
final XMLWriter xmlWriter = new XMLWriter(out, fmt) {
@Override
protected void writeString(String text) throws IOException {
if ((text != null) && (text.length() > 0)) {
if (isEscapeText()) {
text = escapeElementEntities(text);
}

if (getOutputFormat().isTrimText()) {
boolean first = true;
StringTokenizer tokenizer = new StringTokenizer(text, " \t\r\f");

int newLinesCount = 0;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();

int newLines = StringUtils.countMatches(token, '\n');
if (newLines > 0) {
newLinesCount += newLines;
continue;
} else if (newLinesCount > 1) {
writer.write("\n");
newLinesCount = 0;
}

if (first) {
first = false;

if (lastOutputNodeType == Node.TEXT_NODE) {
writer.write(" ");
}
} else {
writer.write(" ");
}

writer.write(token);
lastOutputNodeType = Node.TEXT_NODE;
}
if (newLinesCount > 1) writer.write("\n");
} else {
lastOutputNodeType = Node.TEXT_NODE;
writer.write(text);
}
}
}
};
xmlWriter.write(xmlDoc);
xmlWriter.flush();
}
Expand Down