在 Java DOM 中从 XML 获取元素名称

2022-09-02 12:58:11

我想获取元素名称并在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')

答案 1

一种方法是开始从电影标签而不是电影标签中读取。不确定这是否是您要查找的内容!!.

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
: 犯罪: 剧情


答案 2

我建议你阅读XPath。下面是一些示例

例如,要阅读电影的年份,您可以使用XPath...

/mdb/movies/movie/year/text()