java - 使用 XMLPullParser 解析数据时出现问题

标签 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 监视器引用的第 148 行就是这一行

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

最佳答案

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

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();
                        }
                    }
                });
            }
        }
    }

关于java - 使用 XMLPullParser 解析数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654545/

相关文章:

java - 让计分器像 Android 中的计时器一样工作

xml - 在单节点模式下设置 hadoop 时出现问题。

c# - 在 C# 中遍历 XML 样式站点地图文件

android - 找不到参数的方法 include() [ :app] on root project Android Studio

java - 是否可以使用注释处理器创建静态嵌套类?

java - Eclipse - 内容辅助不适用于对象

c# - 将多个XML转换为JSON列表

android-studio - 在 Android Studio 中使用 assembleRelease 编译 apk 时 proguardRelease FAILED

android - 来自 androidx 和 com.android.support 的重复类

java - java DOM 解析器异常