我想获取元素名称并在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')
答案 0 :(得分:18)
一种方法是从电影标签而不是电影标签开始阅读。不确定这是不是你要找的!!
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());
}
输出:
:教父
:教父
:1972年 : 罪案剧
答案 1 :(得分:3)
答案 2 :(得分:0)
我遇到了同样的问题,这是我的实现方式,
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";
}