问题描述
我想获取元素名称并在XML中打印数据,但不知道如何在特定元素下获取数据。
I want to get the element name and print the data in the XML, but not sure how to get data under specific element.
这是XML示例和我的代码
Here 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());
我只想得到电影里面的元素。但是以下代码还在执行者内部读取
< movie idref =vertigo/>
(如果我想获取内容,则会导致Nullpointer异常) ;我想知道是否有任何可能的方法来避免使用DOM读取下的性能?
I only want to get the element inside movie. but the following code also reads the<movie idref="vertigo"/>
inside the performer(causes Nullpointer exception if I want to get the content); I'm wondering if there is any possible way to avoid read the under Performance by using DOM?
NodeList nodes = doc.getElementsByTagName("movie");
我的最终输出电影应该像这样
My final output for the first movie should look like this
('godfather', 'The Godfather', '1972', 'Crime;Drama')
推荐答案
这样做的一个方法是从电影标签开始阅读而不是电影标签。不知道这是你正在寻找的!
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());
}
输出:
这篇关于在Java DOM中从XML获取元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!