使用XMLPullParser

时间:2018-02-07 01:22:28

标签: java xml android-studio rss xmlpullparser

大家好,昨天回答了生活在同一个国家/地区的用户的问题,我决定开始玩他问过他的问题的xml数据。我已经能够正确地提取这些数据,但现在我正在尝试解析它,我收到一个错误,我希望你们其中一个人知道解决方案。

MainActivity.java片段

public void run()
        {

            URL aurl;
            URLConnection yc;
            BufferedReader in = null;
            String inputLine = "";


            Log.e("MyTag","in run");

            try
            {
                Log.e("MyTag","in try");
                aurl = new URL(url);
                yc = aurl.openConnection();
                in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                //
                // Throw away the first 2 header lines before parsing
                //
                //
                //
                while ((inputLine = in.readLine()) != null)
                {
                    result = result + inputLine;
                    Log.e("MyTag",inputLine);
                }
                in.close();
            }

            catch (IOException ae)
            {
                Log.e("MyTag", "ioexception");
            }



            //@Override
            //public boolean onCreateOptionsMenu(Menu menu) {
            //Inflate the menu; this adds items to the action bar if it is present.
                    //getMenuInflater().inflate(R.menu.activity_main, menu);
            //return true;
        //}

            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Log.d("UI thread", "I am the UI thread");
                    ListView listView = (ListView) findViewById(R.id.listView1);
                    List<TravelIssue> travelIssues = null;
                    try {
                        XmlPullParserHandler parser = new XmlPullParserHandler();
                        InputStream is= getAssets().open(result);
                        travelIssues = parser.parse(is);

                        ArrayAdapter<TravelIssue> adapter =new ArrayAdapter<TravelIssue>(MainActivity.this,android.R.layout.simple_list_item_1, travelIssues);
                        listView.setAdapter(adapter);
                        urlInput.setText("");
                        urlInput.setText(is.toString());
                    } catch (IOException e) {e.printStackTrace();}

                }

            });
        }

    }



XmlPullParserHandler
    int eventType = parser.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    String tagname = parser.getName();
                    switch (eventType) {
                        case XmlPullParser.START_TAG:
                            if (tagname.equalsIgnoreCase("item")) {
                                // create a new instance of travelIssue
                                travelIssue = new TravelIssue();
                            }
                            break;

                        case XmlPullParser.TEXT:
                            text = parser.getText();
                            break;

                        case XmlPullParser.END_TAG:
                            if (tagname.equalsIgnoreCase("item")) {
                                // add travelIssue object to list
                                travelIssues.add(travelIssue);
                            }else if (tagname.equalsIgnoreCase("title")) {
                                travelIssue.setTitle(text);
                            }  else if (tagname.equalsIgnoreCase("description")) {
                                travelIssue.setDescription(text);
                            } else if (tagname.equalsIgnoreCase("link")) {
                                travelIssue.setLink(text);
                            } else if (tagname.equalsIgnoreCase("georss:point")) {
                                travelIssue.setGeorss(text);
                            } else if (tagname.equalsIgnoreCase("author")) {
                                travelIssue.setAuthor(text);
                            } else if (tagname.equalsIgnoreCase("comments")) {
                                travelIssue.setComments(text);
                            } else if (tagname.equalsIgnoreCase("pubDate")) {
                                travelIssue.setPubDate(text);
                            }
                            break;

                        default:
                            break;

Android监视器输出

    <?xml version="1.0" encoding="iso-8859-1"?>
    02-07 01:00:18.215 7212-7352/? E/MyTag: <rss version="2.0" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">
    02-07 01:00:18.215 7212-7352/? E/MyTag:   <channel>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <title>Traffic Scotland - Current Incidents</title>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <description>Current incidents on the road network e.g. accidents</description>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <link>https://trafficscotland.org/currentincidents/</link>
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <language />
    02-07 01:00:18.215 7212-7352/? E/MyTag:     <copyright />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <managingEditor />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <webMaster />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <lastBuildDate>Tue, 06 Feb 2018 22:41:52 GMT</lastBuildDate>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <docs>https://trafficscotland.org/rss/</docs>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <rating />
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <generator>Traffic Scotland | www.trafficscotland.org</generator>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <ttl>5</ttl>
    02-07 01:00:18.216 7212-7352/? E/MyTag:     <item>
    02-07 01:00:18.216 7212-7352/? E/MyTag:       <title>Lothian &amp; Borders and South-West Scotland - Low temperature</title>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <link>http://tscot.org/01a8157</link>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <georss:point>55.634505 -3.418843</georss:point>
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <author />
    02-07 01:00:18.217 7212-7352/? E/MyTag:       <comments />
    02-07 01:00:18.220 7212-7352/? E/MyTag:       <pubDate>Tue, 06 Feb 2018 21:34:33 GMT</pubDate>
    02-07 01:00:18.220 7212-7352/? E/MyTag:     </item>
    ead: I am the UI thread
02-07 01:00:18.249 7212-7212/? W/System.err: java.io.FileNotFoundException: <?xml version="1.0" encoding="iso-8859-1"?><rss version="2.0" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">  <channel>    <title>Traffic Scotland - Current Incidents</title>    <description>Current incidents on the road network e.g. accidents</description>    <link>https://trafficscotland.org/currentincidents/</link>    <language />    <copyright />    <managingEditor />    <webMaster />    <lastBuildDate>Tue, 06 Feb 2018 22:41:52 GMT</lastBuildDate>    <docs>https://trafficscotland.org/rss/</docs>    <rating />    <generator>Traffic Scotland | www.trafficscotland.org</generator>    <ttl>5</ttl>    <item>      <title>Lothian &amp; Borders and South-West Scotland - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8157</link>      <georss:point>55.634505 -3.418843</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:34:33 GMT</pubDate>    </item>    <item>      <title>Strathclyde - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8158</link>      <georss:point>55.85579 -4.258607</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:35:15 GMT</pubDate>    </item>    <item>      <title>Central, Tayside and Fife  - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8159</link>      <georss:point>56.139467 -3.654317</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:36:02 GMT</pubDate>    </item>    <item>      <title>Grampian - Low temperature</title>      <description>Road users are advised to drive with care due to low temperatures and the risk of ice currently affecting driving conditions on many roads throughout the region.</description>      <link>http://tscot.org/01a8160</link>      <georss:point>57.163647 -2.321385</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 21:36:27 GMT</pubDate>    </item>    <item>      <title>M77 Lanes from M77 to M8 J22 - Closure</title>      <description>There is no access from the M77 Northbound to the M8 Eastbound at Junction 22 due to essential overnight roadworks. Motorists are advised to use the available signed diversion route and should allow extra time for their journey.</description>      <link>http://tscot.org/01c189481</link>      <georss:point>55.848812447526 -4.29817817744965</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 19:55:04 GMT</pubDate>    </item>    <item>      <title>M8 J2 Westbound - slip off - Closure</title>      <description>M8(W) J2 Claylands exit slip to M9 is closed.  Drivers are advised to approach with caution and allow for longer than normal journey times.</description>      <link>http://tscot.org/01c189482</link>      <georss:point>55.9255161091877 -3.39157029498306</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 20:10:23 GMT</pubDate>    </item>    <item>      <title>M80 M8 Slip - M80 Main Carriageway - Closure</title>      <description>The M80 is closed Southbound at Junction 1 due to essential overnight roadworks.Motorists are advised to use the available signed diversion route and should allow extra time for their journey</description>      <link>http://tscot.org/01c189483</link>      <georss:point>55.8747347613743 -4.19821267415898</georss:point>      <author />      <comments />      <pubDate>Tue, 06 Feb 2018 20:23:55 GMT</pubDate>    </item>   

    02-07 01:00:18.250 7212-7212/? W/System.err:     at android.content.res.AssetManager.openAsset(Native Method)
    02-07 01:00:18.250 7212-7212/? W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:360)
    02-07 01:00:18.251 7212-7212/? W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:334)
    02-07 01:00:18.251 7212-7212/? W/System.err:     at labstuff.gcu.owencannon.org.assignment.MainActivity$Task$1.run(MainActivity.java:148)

当按下拉入数据的相应按钮时程序不显示任何内容,我是android studio的新手(实际上刚开始学习它因为我需要在今年晚些时候使用它)所以任何了解更多的人的帮助非常感谢谢谢!

编辑:感觉就像我应该添加Android监视器引用的这一行是这一行

InputStream is= getAssets().open(result);

1 个答案:

答案 0 :(得分:0)

如上面的评论所述,我设法通过将runnable方法更改为以下来解决解析问题。

MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Log.d("UI thread", "I am the UI thread");
                        try{
                            ListView lv = (ListView) findViewById(R.id.listView1);
                            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                            SAXParser parser = parserFactory.newSAXParser();
                            DefaultHandler handler = new DefaultHandler(){
                                String currentValue = "";
                                boolean currentElement = false;
                                public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
                                    currentElement = true;
                                    currentValue = "";
                                    if(localName.equals("item")){
                                        rss = new HashMap<>();
                                    }
                                }
                                public void endElement(String uri, String localName, String qName) throws SAXException {
                                    currentElement = false;
                                    if (localName.equalsIgnoreCase("title"))
                                        rss.put("title", currentValue);
                                    else if (localName.equalsIgnoreCase("description"))
                                        rss.put("description", currentValue);
                                    else if (localName.equalsIgnoreCase("link"))
                                        rss.put("link", currentValue);
                                    else if (localName.equalsIgnoreCase("georss:point"))
                                        rss.put("georss:point", currentValue);
                                    else if (localName.equalsIgnoreCase("author"))
                                        rss.put("author", currentValue);
                                    else if (localName.equalsIgnoreCase("comments"))
                                        rss.put("comments", currentValue);
                                    else if (localName.equalsIgnoreCase("pubDate"))
                                        rss.put("pubDate", currentValue);
                                    else if (localName.equalsIgnoreCase("item"))
                                        RSSList.add(rss);
                                }
                                @Override
                                public void characters(char[] ch, int start, int length) throws SAXException {
                                    if (currentElement) {
                                        currentValue = currentValue +  new String(ch, start, length);
                                    }
                                }
                            };
                            parser.parse(new InputSource(new StringReader(result)), handler);
                            ListAdapter adapter = new SimpleAdapter(MainActivity.this, RSSList, R.layout.list_row,new String[]{"title","description","link","georss:point","author","comments","pubDate"},
                                    new int[]{R.id.title, R.id.description, R.id.link, R.id.georss, R.id.author, R.id.comments, R.id.pubdate});
                            lv.setAdapter(adapter);
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }