How to format string to single string, StringUtils?

I have a line that I pass log4j so that it is written to a file, the contents of this line is XML, and it is formatted on several lines with indentations, etc., to make reading easier.

However, I would like the XML to be on the same line, how can I do this? I looked at StringUtils, I think I could remove tabs and carriage returns, but should there be a cleaner way?

thanks

+4
source share
3 answers

I would replace regexp with it. It is not very efficient, but it will certainly be faster than XML parsing!

This is not verified:

String cleaned = original.replaceAll("\\s*[\\r\\n]+\\s*", "").trim(); 

If I didnโ€™t work, this will eliminate all line terminators, as well as any spaces immediately after these line terminators. The space at the beginning of the pattern should kill any trailing spaces on separate lines. trim() discarded for good measure to exclude spaces at the beginning of the first line and at the end of the last.

+5
source

Maybe 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); } 
+1
source
 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(); } 
0
source

Source: https://habr.com/ru/post/1315944/


All Articles