在 Java DOM 中从 XML 获取元素名称
我想获取元素名称并在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());
我只想在电影中获得元素。但是下面的代码也读取了执行者的内部(如果我想获取内容,则会导致Nullpointer异常);我想知道是否有任何可能的方法来避免通过使用DOM来读取性能下?<movie idref="vertigo"/>
NodeList nodes = doc.getElementsByTagName("movie");
我第一部电影的最终输出应该看起来像这样
('godfather', 'The Godfather', '1972', 'Crime;Drama')