gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:41:57 26 4
gpt4 key购买 nike

我有一个 rss 提要,其中每个项目标签中都有两个名为类别的标签。我想得到第一个的值,但不幸的是我得到了第二个的值。这是我的代码:

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

最佳答案

如果您想从当前 item 节点获取第一个 category 然后使用 Element.getElementsByTagName("category") 获取所有类别节点在 NodeList 中,然后使用 NodeList.item(0)NodeList 中获取第一个类别 Element 这样做:

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());

关于带有 DOM 的 Android 解析 xml - 相同命名的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16842756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com