How to parse an RSS feed with XmlPullParser?

后端 未结 1 1937
囚心锁ツ
囚心锁ツ 2021-01-02 06:57

I would like to parse a RSS feed. My question is how I can parse all tags between the and tags.

Given this very

1条回答
  •  伪装坚强ぢ
    2021-01-02 07:43

    Try the below.

    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(false);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(url.openConnection().getInputStream(), "UTF_8"); 
        //xpp.setInput(getInputStream(url), "UTF-8");
    
        boolean insideItem = false;
    
        // Returns the type of current event: START_TAG, END_TAG, etc..
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
    
                if (xpp.getName().equalsIgnoreCase("item")) {
                    insideItem = true;
                } 
                else if(xpp.getName().equalsIgnoreCase("title")) 
                {
    
                }
            }
            eventType = xpp.next(); //move to next element
        }
    
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Edit:

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(false);
    XmlPullParser xpp = factory.newPullParser();
    xpp.setInput(open,null);
    // xpp.setInput(getInputStream(url), "UTF-8");
    
    boolean insideItem = false;
    
    // Returns the type of current event: START_TAG, END_TAG, etc..
    int eventType = xpp.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
    
            if (xpp.getName().equalsIgnoreCase("item")) {
                insideItem = true;
            } else if (xpp.getName().equalsIgnoreCase("title")) {
                if (insideItem)
                    Log.i("....",xpp.nextText()); // extract the headline
            } else if (xpp.getName().equalsIgnoreCase("link")) {
                if (insideItem)
                    Log.i("....",xpp.nextText());  // extract the link of article
            }
        } else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
            insideItem = false;
        }
    
        eventType = xpp.next(); // move to next element
    }
    

    Output

    www.example.com/example1
    Example title 1
    www.example.com/example2
    Example title 2
    

    0 讨论(0)
提交回复
热议问题