Android报价未被解析

时间:2011-03-25 10:50:24

标签: android parser-generator xml-parsing

我使用以下代码来解析RSS提要。如果引号出现,它不起作用。请帮忙。

public static ArrayList<RssItem> getRssItems(String feedUrl) {

        ArrayList<RssItem> rssItems = new ArrayList<RssItem>();

        try {
            //open an URL connection make GET to the server and 
            //take xml RSS data
            URL url = new URL(feedUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();

                //DocumentBuilderFactory, DocumentBuilder are used for 
                //xml parsing
                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                //using db (Document Builder) parse xml data and assign
                //it to Element
                Document document = db.parse(is);
                Element element = document.getDocumentElement();

                //take rss nodes to NodeList
                NodeList nodeList = element.getElementsByTagName("item");

                if (nodeList.getLength() > 0) {
                    for (int i = 0; i < nodeList.getLength(); i++) {

                        //take each entry (corresponds to <item></item> tags in 
                        //xml data

                        Element entry = (Element) nodeList.item(i);

                        Element _titleE = (Element) entry.getElementsByTagName(
                                "title").item(0);
                        Element _descriptionE = (Element) entry
                                .getElementsByTagName("description").item(0);
                        Element _pubDateE = (Element) entry
                                .getElementsByTagName("pubDate").item(0);
                        Element _linkE = (Element) entry.getElementsByTagName(
                                "link").item(0);

                        String _title = _titleE.getFirstChild().getNodeValue();
                        String _description = _descriptionE.getFirstChild().getNodeValue();
                        Date _pubDate = new Date(_pubDateE.getFirstChild().getNodeValue());
                        String _link = _linkE.getFirstChild().getNodeValue();

                        //create RssItemObject and add it to the ArrayList
                        RssItem rssItem = new RssItem(_title, _description,
                                _pubDate, _link);

                        rssItems.add(rssItem);
                    }
                }

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

        return rssItems;
    }

1 个答案:

答案 0 :(得分:0)

您假设元素中只有一个文本节点(getFirstChild().getNodeValue())。这是一个错误的假设。您需要遍历元素的所有子节点并组合文本节点。