Get element name from XML in Java DOM
I had the same issue, this is my implementation,
public String getTagValue(org.w3c.dom.Document xmlDoc, String tagName) throws Exception {
xmlDoc.getDocumentElement().normalize();
NodeList nodeList = xmlDoc.getElementsByTagName(tagName);
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node nNode = nodeList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode;
return eElement.getFirstChild().getNodeValue();
}
}
return "-1";
}
One way to do this is to start reading from movies tag instead of the movie tag. Not sure if this is what you are looking for !!.
NodeList nodes = doc.getElementsByTagName("movies");
Element element = (Element) nodes.item(0);
NodeList movieList = element.getElementsByTagName("movie");
for (int i = 0; i < movieList.getLength(); i++) {
Element movieElement = (Element) movieList.item(i);
System.out.println(movieElement.getAttributes().getNamedItem("id").getNodeValue());
NodeList name = movieElement.getElementsByTagName("title");
NodeList year = movieElement.getElementsByTagName("year");
NodeList genres = movieElement.getElementsByTagName("genres");
Element genreline = (Element) genres.item(0);
System.out.println(name.item(0).getFirstChild().getTextContent());
System.out.println(year.item(0).getFirstChild().getTextContent());
System.out.println(genreline.getElementsByTagName("genre").item(0).getTextContent()
+ ":" + genreline.getElementsByTagName("genre").item(1).getTextContent());
}
Output :
: godfather
: The Godfather
: 1972
: Crime:Drama
I suggest you read up on XPath. Here are a few examples.
For example, to read the year for your movies you could use the XPath...
/mdb/movies/movie/year/text()