首页 > 解决方案 > Android XML 解析错误

问题描述

我试图通过我之前的帖子从 URL 开始 XML 解析:Parsing XML on Android

因此,我尝试使用 InputStream 获取 XML 文件并使用 DocumentBuilder 解析其中的文本。

我试图使用 SharedPreferences 离线存储我的 XML 文件。

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string>
    <name>username</name>
    <value>mium</value>
</string>

这是我的 XML 文件。

  private boolean parseXML(String target){
    cache_string = getSharedPreferences("cache_userfiles", Context.MODE_PRIVATE);
    cache_string_editor = cache_string.edit();
    cache_string_editor.apply();
    try {
        URL url = new URL(target);
        InputStream inputStream = url.openStream();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(inputStream);
        Element element = document.getDocumentElement();
        element.normalize();
        NodeList nodeList = document.getElementsByTagName("string");
        for (int current=0; current < nodeList.getLength(); current++){
            Node node = nodeList.item(current);
            if (node.getNodeType() == Node.ELEMENT_NODE){
                Element element_specific = (Element) node;
                cache_string_editor.putString(getValue("name", element_specific), getValue("value", element_specific));
                cache_string_editor.apply();
            }
        }
        return true;
    } catch (Exception e){
        e.printStackTrace();
        return false;
    }
}

这是我的解析代码。

要使用此代码,在我的主线程中,我使用了:

if (parseXML("http://www.myserver.com/file.xml")){
    Log.d(TAG, "Success");
}

但是,我不断收到 android.os.NetworkOnMainThreadException。我尝试添加线程和处理程序,但它一直给我一个错误。有什么问题?我知道它无法在主线程上处理网络进程,但我不知道如何解决这个问题。

标签: androidxmlparsingnetworkonmainthread

解决方案


您不能在主线程上使用网络,因为它会阻塞 UI 组件。您需要为此使用 AsyncTask 。

new AsyncTask<Void ,Void ,Boolean>(){
            @Override
            protected Boolean doInBackground(Void... voids) {
                return parseXML("http://www.myserver.com/file.xml");
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                Log.d(TAG, "Success "+aBoolean);
            }
        }.execute();

推荐阅读