【发布时间】:2013-05-30 17:47:08
【问题描述】:
我有一个 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
【问题讨论】:
-
请显示您的 rss xml 以获得更多帮助
-
你试过
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()); -
你是最棒的!!那行得通!!请把它作为答案发布以接受它!
标签: android dom xml-parsing rss