簡體   English   中英

android utf-8文件解析

[英]android utf-8 file parsing

我有一些以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()工作?

在這一行:

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

您正在使用平台默認編碼從stream讀取。 幾乎可以肯定這不是您想要的。 您需要檢查XML以獲取實際的編碼,並且正確的編碼方式有些復雜

幸運的是,每個理智的XML解析器(包括Java / Android解析器)都可以自己完成。 為了使XML解析器能夠做到這一點,只需傳遞stream本身,而不是嘗試手動讀取它即可。

InputSource inputSource = new InputSource(stream);

您的Java字符串默認為UTF-16編碼。 如果您不能按照@Joachim Sauer的建議使用InputStream,請嘗試以下操作:

Document doc = db.parse(new ByteArrayInputStream(xmlData.getBytes())); 

您很有可能使用帶有BOM標記(字節順序標記)的XML文件。

使用API​​來檢測BOM表中的編碼

或者,對文件進行預處理,以使不存在BOM。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM