gpt4 book ai didi

android - 如何在android中读取XML父节点标签值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:39 25 4
gpt4 key购买 nike

我有一个读取 XML 节点的 java 代码,我想在加法中添加并且还想读取父节点值。

我的 XML 文件示例如下:

 <breakfast_menu><food id=1><name> Belgian Waffles </name><price> $5.95 </price><description> two of our famous Belgian Waffles with plenty of real maple syrup </description><calories> 650 </calories></food><food id=2><name>Strawberry Belgian waffles</name><price>$7.95</price><description>light Belgian waffles covered with strawberries and whipped cream</description><calories>900</calories></food></breakfast_menu>

我解析 xml 的代码是:

public static String getProductItem(String pid, String item) {

try {
url = new URL("");
urlConnection = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {

}

try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
}
try {
doc = dBuilder.parse(urlConnection.getInputStream());
} catch (SAXException e) {

} catch (IOException e) {

}

doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("food");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;



data = getTagValue(item, eElement);



}
}

doc = null;
dBuilder = null;

return data;

}


private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();
}

我想做的是读取食物的“id”值,所以如果我正在搜索食物,它只会检查那些 id 与食物节点 id 匹配的食物节点。

如果我按标签 ID 读取,它会读取所有标签,而不是特定的一个标签。如何实现?

最佳答案

也许我错过了什么,是不是您正在寻找的只是 String id = eElement.getAttribute("id");

您可能想要研究使用 XPath 来提取您的 DOM。 getElementsByTagName 有一个忽略文档结构的恼人习惯。 (还应该使用命名空间和 getElementsByTagNameNS :))

关于android - 如何在android中读取XML父节点标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2808793/

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