I have a xml file :
<root>
<book
name="Science1"
author="XYZ1">
</book>
<book
name="Science2"
author="XYZ2">
</book>
</root>
I want to get the value of name and author. Java code to parse the above :
Document doc = null;
try {
InputStream is = getResources().openRawResource(R.raw.xmldata);//newfile
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(is));
NodeList nl1 = doc.getElementsByTagName("book");
for (int i = 0; i < nl1.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl1.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_AUTHOR,parser.getValue(e, KEY_AUTHOR));
Log.d("Debug","Value + " + parser.getValue(e, KEY_NAME) + " " + parser.getValue(e, KEY_AUTHOR));
// adding HashList to ArrayList
menuItems.add(map);
}
}
catch(Exception e)
{
e.printStackTrace();
}
What I am missing here, as when I print the tag value, I don't get any value.
Please suggest / help how can I read this format ? If this format has any other dependency like schema / DTD to be provided, let me know, as I am totally unaware of the correct flow. Please suggest me some site as well where I can validate my xml file as well.
Bring the xml-File in this format:
<root>
<book name="Science1"
author="XYZ1"/>
<book name="Science2"
author="XYZ2" />
</root>
And than for your for-loop:
for (int temp = 0; temp < nl1.getLength(); temp++) {
HashMap<String, String> map = new HashMap<String, String>();
Node nNode = nl1.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
map.put(KEY_NAME, eElement.getAttribute("name"));
map.put(KEY_AUTHOR, eElement.getAttribute("author"));
menuItems.add(map);
}
}
Hope it helps