【发布时间】:2011-10-05 10:36:41
【问题描述】:
我尝试使用 sax 解析器从输入流中解析 xml。输入流不断地从套接字获取传入的 xml。 '\n' 用作 xml 数据之间的分隔符。这就是 xml 的样子
<?xml version="1.0" encoding="UTF-8"?>
<response processor="header" callback="comheader">
<properties>
<timezone>Asia%2FBeirut</timezone>
<rawoffset>7200000</rawoffset>
<to_date>1319256000000</to_date>
<dstrawoffset>10800000</dstrawoffset>
</properties>
</response>
\n
<event type="progress" time="1317788744214">
<param key="callback">todayactions</param>
<param key="percent">10</param>
<param key="msg">MAPPING</param>
</event>
<event type="progress" time="1317788744216">
<param key="callback">todayactions</param>
<param key="percent">20</param><param key="msg">MAPPING</param>
</event>
\n
<?xml version="1.0" encoding="UTF-8"?>
<response processor="header" callback="comheader">
<properties>
<timezone>Asia%2FBeirut</timezone>
<rawoffset>7200000</rawoffset>
<to_date>1319256000000</to_date>
<dstrawoffset>10800000</dstrawoffset>
</properties>
</response>
这对我们的 iphone 项目非常有效,因为我们将字符提升到 \n 并将其存储在字符串中并使用 dom 解析器。
但是当我尝试为 android 执行此操作时,字符串不是一个选项,因为它给了我们 OutOfMemory 异常。所以我们将输入流直接设置为 SaxParser 它一直工作到 \n 字符,之后它给我们异常
org.apache.harmony.xml.ExpatParser$ParseException:在第 2 行,第 2 列 0:文档元素后的垃圾
所以我尝试过滤输入流以跳过“\n”字符。我创建了一个 FilterStreamReader 但我没有成功,看来我的读取功能没有完成这项工作。这是我的代码。
public class FilterStreamReader extends InputStreamReader {
public FilterStreamReader(InputStream in, String enc)
throws UnsupportedEncodingException {
super(in, enc);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int read = super.read(cbuf, off, len);
Log.e("Reader",Character.toString((char)read));
if (read == -1) {
return -1;
}
int pos = off - 1;
for (int readPos = off; readPos < off + read; readPos++) {
if (read == '\n') {
pos++;
} else {
continue;
}
if (pos < readPos) {
cbuf[pos] = cbuf[readPos];
}
}
return pos - off + 1;
}
有人可以帮我过滤输入流的\n吗?
编辑 根据格雷厄姆所说的,我能够通过删除所有文档类型并添加我自己的开始和结束标记来解析整个数据。所以我不太确定我的问题不是单独过滤 '\n' 。你怎么能解析像这样不断出现的xml?
【问题讨论】:
-
检查是否存在 \r 符号,具体取决于准备原始文件的底层操作系统,您可能有 \r\n 而不是单个 \r(对于 Linux)
标签: java android xml inputstream sax