我想要获取元素名称并在
XML中打印数据,但不知道如何在特定元素下获取数据.
这是XML示例和我的代码.
<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());
我只想得到电影中的元素.但以下代码也读取
< movie idref =“vertigo”/>在表演者的内部(如果我想得到内容,会导致Nullpointer异常);我想知道是否有任何可能的方法来避免使用DOM读取下面的性能?
NodeList nodes = doc.getElementsByTagName("movie");
我的第一部电影的最终输出应该是这样的
('godfather','The Godfather','1972','Crime;Drama')
解决方法
一种方法是从电影标签开始阅读而不是电影标签.不知道这是你正在寻找的!
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()); }
输出:
: godfather : The Godfather : 1972 : Crime:Drama