Android的UTF-8文件解析 [英] android utf-8 file parsing
问题描述
我有恩是在 codeD UTF-8
一些的.xml
文件。但每当我尝试解析他们对我的平板电脑(的想法垫,联想的Android 3.1),我得到了同样的错误:
I have some .xml
files that are encoded in UTF-8
. But whenever I try to parse them on my tablet (idea pad, lenovo, android 3.1), I get the same error:
org.xml.SAXParseException: Unexpected token (position: TEXT @1:2 in
java.io.StringReader@40bdaef8).
这些是抛出异常的行:
These are the lines that throw the exception:
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()
工作
I don't want to convert them to ANSI
, so is there any way to make the db.parse()
work?
推荐答案
目前行:
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
您是从使用平台默认的编码流
读书。这是的几乎肯定的不是你想要的。你需要检查XML为实际编码要做到这一点是的有点复杂。
You're reading from stream
using the platform default encoding. That's almost certainly not what you want. You'd need to check the XML for for the actual encoding and the correct way to do that is somewhat complicated.
幸运的是,每一个理智的XML解析器(包括Java / Android的一个)可以做到这一点靠自己。为了使XML解析器这样做,只是通过流
本身,而不是试图手动读取它。在
Luckily, every sane XML parser (including the Java/Android one) can do that on its own. To make the XML parser do that, simply pass in the stream
itself instead of trying to read it manually.
InputSource inputSource = new InputSource(stream);
这篇关于Android的UTF-8文件解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!