我创建了一个扩展 SAX DefaultHandler 的类。为了获取标签之间的值,我这样做:
private static class MyHandler extends DefaultHandler {
private String str;
@Override
public void characters(char ch[], int start, int length) throws
SAXException {
String current = new String(ch, start, length);
str+=current;
}
}
如果结束标记位于同一行,但如果 xml 如下所示:
<string name="sentence">The fox runs\nover the hill into the pasture
</string>
它呈现为:
"The fox runs\nover the hill into the pasture
"
而不是
"the fox runs
over the hill into the pasture"
我不能使用trim(),因为字符串可能看起来像“The Fox run\nover the hill into the Pasture\n”
最佳答案
这里的关键是标签内的空白是否重要。如果它不重要,您可以删除多余的空格。这可以通过一个简单的正则表达式来完成。
str += current.replaceAll("\\s{2,}$", "")
如果行尾至少包含两个空格(无论是空格+换行符还是任何其他组合),此正则表达式将修剪该行。如果该行全是空格,它将被完全删除。
但是它将保持不变
The fox runs\nover the hill into the pasture\n
如果您想处理用户意外键入 \n\n
而不仅仅是 \n
的情况,您可以稍作更改
str += current.replaceAll("\\s{2,}$", "\n")
关于java - 如何使 SAX DefaultHandler 忽略隐式换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200494/