0

我正在尝试在我的 android 应用程序中解析 rss 提要。我的提要包含很多带有“标签”标签的项目,看起来像

<item>
<title> title </title>
<link> link </link>
<pubDate> date </pubDate>
<description> description </description>

<tags>
<tag id="1">first</tag>
<tag id="2">second</tag>
<tag id="3">third</tag>
</tags>

</item>

我的问题:我如何才能选择仅具有特定“标签”的项目,例如。标签=“第二”?

4

1 回答 1

0

重写了我的 Xml Factory 课程,它应该会引导你走上正轨。

/**
 * 
 * @author hsigmond
 *
 */
public class RssXmlFactory {

    public static ArrayList<RSSItem> parseResult(final String rssDataContent,String tag_id) throws ParserConfigurationException,
            SAXException, IOException {

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        public String mItemTagID=tag_id;//"2"

        RSSItemsHandler parser = new RSSItemsHandler();
         xr.setContentHandler(parser);
        StringReader sr = new StringReader(rssDataContent);
        InputSource is = new InputSource(sr);
        xr.parse(is);

        return parser.mItemList;

    }

}


class RSSItemsHandler extends DefaultHandler {

    private StringBuilder mSb = new StringBuilder();
    public ArrayList<RSSItem> mItemList = new ArrayList<RSSItem>();
    public RSSItem mCurrentRssItem = null;
    public String mItemTitle="";


    @Override
    public void startElement(final String namespaceURI, final String localName, final String qName,
            final Attributes atts) throws SAXException {
        mSb.setLength(0);

        if (localName.equals(XMLTag.TAG_RSS_ITEM_ROOT)) {
            /** Get the rss item title attribute value */
            mItemTitle=atts.getValue(XMLTag.TAG_RSS_ITEM_TITLE);
            //#TODO Log result
        }

        else if (localName.equals(XMLTag.TAG_RSS_ITEM_TAG_ROOT)) {
        //This is where you check if the TAG equals id=2, did not have the time to check if it works yet, it's late...
        if(atts.getValue(XMLTag.TAG_RSS_ITEM_TAG_ID).equalsIgnoreCase(mItemTagID)){//id="2"
             mCurrentRssItem = new RSSItem();
            /** Set item title attribute value */
            mCurrentRssItem.title=mItemTitle;
                //#TODO Log result
          }     
        }
    }

    @Override
    public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException {

        if (localName.equals(XMLTag.TAG_RSS_ITEM_ROOT)) {
            mItemList.add(mCurrentRssItem);

        } else if (localName.equals(XMLTag.TAG_RSS_ITEM_TAG_ROOT)) {
            mCurrentRssItem.tag = mSb.toString();         
        } 
    }

    @Override
    public void characters(final char[] ch, final int start, final int length) throws SAXException {
        super.characters(ch, start, length);
        mSb.append(ch, start, length);
    }
}
}

有关如何在 Android 上处理 XML 的更多详细信息,请参见此处:http ://www.ibm.com/developerworks/opensource/library/x-android/index.html

于 2012-12-28T02:19:16.077 回答