我创建了一个扩展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 the string \n“。
发布于 2016-05-13 04:00:14
这里的关键是标记中的空格是否重要。如果不重要,你可以去掉多余的空格。这可以通过一个简单的正则表达式来完成。
str += current.replaceAll("\\s{2,}$", "")
如果该行末尾至少包含两个空格(空格+新行或任何其他组合),则此正则表达式将修剪该行。如果该行全是空格,它将被完全删除。
但是,它将保持不变
狐狸跑过小山进入牧场\n
如果您想要处理用户不小心输入\n\n
而不只是\n
的情况,您可以稍作更改
str += current.replaceAll("\\s{2,}$", "\n")
https://stackoverflow.com/questions/37200494
复制相似问题