Get the element name from XML in Java DOM
•
Java
I want to get the element name and print the data in XML, but I don't know how to get the data under a specific element
This is the XML sample and my code
<mdb> <movies> <movie id="godfather"> <title>The Godfather</title> <year>1972</year> <directors> <director idref="francisfordcoppola"/> </directors> <genres> <genre>Crime</genre> <genre>Drama</genre> </genres> <cast> <performer> <actor idref="marlonbrando"/> <role>Don Vito Corleone</role> </performer> </cast> </movie> </movies> <performer id="kimnovak"> <name>Marilyn Pauline Novak</name> <dob>1933-02-13</dob> <pob>Chicago,Illinois,USA</pob> <actedin> <movie idref="vertigo"/> </actedin> </performer> </mdb> try { File fXmlFile = new File(filename); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); NodeList nodes = doc.getElementsByTagName("movie"); System.out.println("nodes length"+ nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++){ Element element = (Element) nodes.item(i); NodeList name = element.getElementsByTagName("title"); Element line = (Element) name.item(0); System.out.println(": " + line.getFirstChild().getTextContent());
I just want the elements in the film But the following code also reads < movie Idref = "vertigo" / > inside the performer (if I want to get the content, it will cause nullpointer exception); I wonder if there is any possible way to avoid using DOM to read the following performance?
NodeList nodes = doc.getElementsByTagName("movie");
The final output of my first film should be like this
('godfather','The Godfather','1972','Crime;Drama')
Solution
One way is to start reading from the movie tag instead of the movie tag I don't know what you're 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:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码