如何将字符串格式化为一行,StringUtils?
我有一个字符串,我将其传递给 log4j 以将其记录到文件中,该字符串的内容是 XML,并且它被格式化为带有缩进等的多行,以使其易于阅读。
但是,我希望 XML 全部在一行上,我该怎么做呢?我看过 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会对其进行正则表达式替换。虽然效率不高,但肯定比 XML 解析快!
这是未经测试的:
如果我没有犯错,这将消除所有行终止符以及紧随这些行终止符之后的任何空格。模式开头的空白应消除各行上的任何尾随空白。
trim()
的引入是为了消除第一行开头和最后一行结尾处的空格。I'd throw a regexp replace on it. That's not highly efficient but sure to be faster than XML parsing!
This is untested:
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.也许与 JDom http://www.jdom.org/
Perhaps with JDom http://www.jdom.org/
@corsiKa 的答案,但使用 Java 8+ 可选。另外,我发现使用行分隔符系统属性不能作为
String.split
的正则表达式。@corsiKa's answer, but using Java 8+ Optional. Also, I found that using the line separator system property didn't work as a regex to
String.split
.