Come leggere genitore valore delle variabili nodo XML in Android
-
25-09-2019 - |
Domanda
Ho un codice Java per leggere nodi XML, voglio aggiungere in aggiunta e voglio leggere il valore del nodo genitore anche.
il mio campione file XML è qui sotto:
<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>
e il mio codice per il parsing 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();
}
Quello che voglio fare è quello di leggere il valore "id" di cibo, quindi se se sono alla ricerca di un alimento, solo controlli di quei nodi alimentari, il cui id abbinato il nodo cibo id.
se leggo per tag id, legge tutti i tag non specificamente un tag. Come raggiungerlo?
Soluzione
Forse ho perso quacosa, è solo String id = eElement.getAttribute("id");
che stai cercando?
Si potrebbe voler considerare di usare XPath per andare a prendere dal vostro DOM. getElementsByTagName ha un irritante abitudine di ignorare la struttura del documento. (Inoltre dovrebbe essere utilizzando uno spazio dei nomi e getElementsByTagNameNS :))
Altri suggerimenti
È possibile utilizzare XPath per trovare facilmente un insieme di nodi secondo alcuni criteri. Ad esempio:
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.evaluate("//food[@id=22]", doc, XPathConstants.NODESET);
Questo codice trova tutti i nodi alimentari con un dato id nel documento. XPath è un linguaggio ricco per questo tipo di ricerca.
XPath è disponibile per l'uso in Android dal livello di API 8. Se si tratta di un'opzione per voi, si supponga che il XML è spostata nel progetto
/res/raw/food_list.xml
Dato che, è possibile cercare tutti gli elementi che utilizzano questa sintassi XPath:
//food/@id
L'espressione di ricerca qui sopra restituirà un elenco di tutti id
attributi propri elementi <food>
ovunque si trovino in quanto radice.
Quindi, se quello che vuoi è di recuperare tutti quegli attributi id
, si può fare come segue
InputStream is = getResources().openRawResource(R.raw.food_list);
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
try {
Document doc = fac.newDocumentBuilder().parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr;
try {
expr = xpath.compile("//food/@id");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
// Considering the example XML at the end of this loop you will
// get the ids printed
System.out.println(node.getNodeValue());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
is.close();
} catch (IOException e1) {
e1.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Un riferimento rapido sulla sintassi XPath e un po 'di spiegazione può essere trovata qui .