【问题标题】:Parsing XML file解析 XML 文件
【发布时间】:2014-08-23 05:18:41
【问题描述】:

虽然有很多关于这个主题的资源,但我无法找出我的代码中的错误。我在位置 http://omnicoders.in/test/new.xml 有一个 xml 文件作为我的第一个程序,所以我从 DOM 解析器开始。

这是主要活动的代码

    package com.example.parsexml;

    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;

    import javax.xml.parsers.DocumentBuilder; 
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;

    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.widget.TextView;

    public class XMLMainActivity extends ActionBarActivity {

private static final String TAG = "XML parsing";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xmlmain);

    TextView tv = (TextView) findViewById(R.id.tv_xml);

    URL url;

    try {
        String urlAdd = getString(R.string.xmllink);
        url = new URL(urlAdd);

        URLConnection connection;
        connection = url.openConnection();

        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConnection.getInputStream();

            DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            Document dom = db.parse(in);
            Element docEle = dom.getDocumentElement();

            NodeList nl = docEle.getElementsByTagName("root");

            Element root = (Element) nl.item(0);
            Element blub = (Element) root.getElementsByTagName("blub");
            Element bar = (Element) root.getElementsByTagName("bar");
            Element overflow = (Element) root
                    .getElementsByTagName("overflow");

            String tag1 = blub.getNodeValue();
            String tag2 = bar.getNodeValue();
            String tag3 = overflow.getNodeValue();

            String vinitxml = tag1 + tag2 + tag3;
            tv.setText(vinitxml);
        }

    } catch (MalformedURLException e) {
        Log.d(TAG, "MalformedURLException");
    } catch (IOException e) {
        Log.d(TAG, "IOException");
    } catch (SAXException e) {
        Log.d(TAG, "SAX Exception");
    } catch (ParserConfigurationException e) {
        Log.d(TAG, "Parse Configuration Excetion");
    }
}
    }

string.xml 是

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">ParseXml</string>
<string name="xmllink">http://omnicoders.in/test/new.xml</string>
<string name="action_settings">Settings</string>

</resources>

我的主要 xml 只包含一个文本视图,是的,我也在 android manifest 中使用了互联网权限。

但我的应用程序总是停止并说很遗憾您的应用程序已停止。

【问题讨论】:

  • 你不能运行对 UI 线程的阻塞调用
  • 你好,你能提供上面逻辑的代码sn-p吗?

标签: android xml dom xml-parsing


【解决方案1】:

试试这个方法,希望能帮助你解决问题。

    private TextView tv_xml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv_xml = (TextView) findViewById(R.id.tv_xml);
        new GetXmlFromUrl().execute(getString(R.string.xmllink));
    }

    class GetXmlFromUrl extends AsyncTask<String, Void, String> {
        URL url;
        @Override
        protected String doInBackground(String... params) {
            String reponse="";
            try {
                url = new URL(params[0]);
                URLConnection connection;
                connection = url.openConnection();

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                connection.setRequestProperty("Content-Type", "text/xml");

                int responseCode = httpConnection.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream in = httpConnection.getInputStream();
                    DocumentBuilderFactory dbf = DocumentBuilderFactory
                            .newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document dom = db.parse(in);

                    dom.getDocumentElement().normalize();
                    NodeList nodes = dom.getElementsByTagName("root");

                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node node = nodes.item(i);

                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            String tag1 = getValue("blub", element);
                            String tag2 = getValue("bar", element);
                            String tag3 = getValue("overflow", element);
                            reponse += tag1 +" " +tag2 +" " +tag3;
                        }
                    }


                }
            } catch (Throwable e) {
                e.printStackTrace();
            }

            return reponse;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tv_xml.setText(s);
        }
    }

    private static String getValue(String tag, Element element) {
        NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodes.item(0);
        return node.getNodeValue();
    }

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 2019-02-02
    • 2012-01-01
    • 2014-03-01
    • 2018-09-23
    • 2020-10-22
    • 2023-04-07
    • 2018-04-17
    相关资源
    最近更新 更多