How to format a String onto one line, StringUtils?
I have a String that I'm passing to log4j to have it logged to a file, the contents of that string is XML, and it开发者_运维知识库 is formatted to be on multiple lines with indentations and so forth, to make it easy to read.
However, I would like that XML to be all on one line, how can I do this? I've had a look at StringUtils, I guess I could strip the tabs and carriage returns, but there must be a cleaner way?
Thanks
I'd throw a regexp replace on it. That's not highly efficient but sure to be faster than XML parsing!
This is untested:
String cleaned = original.replaceAll("\\s*[\\r\\n]+\\s*", "").trim();
If I haven't goofed, that will eliminate all line terminators as well as any whitespace immediately following those line terminators. The whitespace at the beginning of the pattern should kill any trailing whitespace on individual lines. trim()
is thrown in for good measure to eliminate whitespace at the start of the first line and the end of the last.
Perhaps with JDom http://www.jdom.org/
public static Document createFromString(final String xml) {
try {
return new SAXBuilder().build(new ByteArrayInputStream(xml.getBytes("UTF-8")));
} catch (JDOMException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String renderRaw(final Document description) {
return renderDocument(description, getRawFormat());
}
public static String renderDocument(final Document description, final Format format) {
return new XMLOutputter(format).outputString(description);
}
String oneline(String multiline) {
String[] lines = multiline.split(System.getProperty("line.separator"));
StringBuilder builder = new StringBuilder();
builder.ensureCapacity(multiline.length()); // prevent resizing
for(String line : lines) builder.append(line);
return builder.toString();
}
精彩评论