【发布时间】:2011-10-25 07:26:31
【问题描述】:
我有一些以UTF-8 编码的.xml 文件。但是每当我尝试在我的平板电脑(idea pad、lenovo、android 3.1)上解析它们时,我都会收到同样的错误:
org.xml.SAXParseException: Unexpected token (position: TEXT @1:2 in
java.io.StringReader@40bdaef8).
这些是引发异常的行:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(new StringReader(xmlData));
Document doc = db.parse(inputSource); // This line throws exception
这是我的输入:
public String getFromFile(ASerializer aserializer) {
String filename = aserializer.toLocalResource();
String data = new String();
try {
InputStream stream = _context.getResources().getAssets().open(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
str.append(line);
}
stream.close();
data = str.toString();
}
catch(Exception e) {
}
return data;
}
XML 文件:
<Results>
<Result title="08/07/2011">
<Field title="Company one" value="030589674"/>
<Field title="Company two" value="081357852"/>
<Field title="Company three" value="093587125"/>
<Field title="Company four" value="095608977"/>
</Result>
<Result title="11/07/2011">
<Field title="Company one" value="030589674"/>
<Field title="Company two" value="081357852"/>
</Result>
</Results>
我不想将它们转换为ANSI,那么有什么方法可以使db.parse() 工作吗?
【问题讨论】:
-
如果你用它显示示例输入真的很有意义
-
你是怎么读到
xmlData的?我怀疑那里出了点问题。 -
使用读取数据的方法编辑我的原始答案。
-
如何加载 xmlData? String 将数据存储为 UTF-16,因此可能是初始化存在问题,或者 XML 已损坏 - 示例会有所帮助。
标签: android parsing exception utf-8 sax