1

我有一个 rss 提要,在每个项目标签中都有两个名为 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 提要是这样的:

<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
4

1 回答 1

2

如果您想category从当前item节点获取第一个,则Element.getElementsByTagName("category")用于获取所有类别节点,NodeList然后用于NodeList.item(0)获取第一个类别ElementNodeList如下所示:

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());
于 2013-05-30T18:25:43.493 回答