带有DOM的Android Parse xml - 相同的命名标签

时间:2013-05-30 17:47:09

标签: android dom xml-parsing rss

我有一个rss feed,在每个item标签中都有两个名为category的标签。我想得到第一个的值,但不幸的是我得到了第二个值。这是我的代码:

   // Create required instances
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                // Parse the xml
                Document doc = db.parse(new InputSource(url.openStream()));
                doc.getDocumentElement().normalize();

                // Get all <item> tags.
                NodeList nl = doc.getElementsByTagName("item");
                int length = nl.getLength();

                // to length einai posa nea tha emfanisei.Edw tou lew ola pou
                // vriskei
                for (int i = 0; i < length; i++) {
                    Node currentNode = nl.item(i);
                    RSSItem _item = new RSSItem();

                    NodeList nchild = currentNode.getChildNodes();
                    int clength = nchild.getLength();

                    // Get the required elements from each Item
                    for (int j = 0; j < clength; j = j + 1) {

                        Node thisNode = nchild.item(j);
                        String theString = null;

                        if (thisNode != null && thisNode.getFirstChild() != null) {
                            theString = thisNode.getFirstChild().getNodeValue();

                        }

                        if (theString != null) {

                            String nodeName = thisNode.getNodeName();
                      ...
....
...

                            if ("category".equals(nodeName)) {

                                /*
                                 * NodeList nlList = nl.item(0).getChildNodes();
                                 * Node nValue2 = (Node) nlList.item(0);
                                 * _item.setCategory(nValue2.getNodeValue());
                                 */

                                _item.setCategory(theString);
                            }
                        }
                    }

编辑:

我的RSS Feed就像:

<item>
<title>my title</title>
<category>Sports</category>
<category>World</category>
</item>

<item>
<title>my title 2</title>
<category>News</category>
<category>Showbiz</category>
</item>
...etc

1 个答案:

答案 0 :(得分:2)

如果您想从当前category节点获取第一个item,请使用Element.getElementsByTagName("category")获取NodeList中的所有类别节点,然后使用NodeList.item(0)Element获取第一个类别NodeList,将其作为:

Element element = (Element) currentNode;
NodeList nodelist = element.getElementsByTagName("category");
Element element1 = (Element) nodelist.item(0);
NodeList category = element1.getChildNodes();
System.out.print("category : " + (category.item(0)).getNodeValue());