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で読み取ると、特に1つのタグではなく、すべてのタグが読み取られます。それを達成する方法は?