2016-04-09 55 views
1

我能夠使用Java在我的XML文檔上運行簡單的查詢,但我期望運行更高級的查詢並且在這樣做時遇到了一些麻煩。使用Java查詢XML

當我想要獲取XML文件中其他演員的姓名時,我能夠獲得本示例的第一個演員(在此例中爲Marlon Brando)的名稱。

我已經使用了迄今爲止的/film/cast,它向我展示了所有演員的名字,以及他們在電影中扮演的角色;我不想要。

請幫忙! 感謝

XML:

<!--?xml version="1.0"?--> 
<film> 
    <title>"Godfather, The"</title> 
    <year>1972</year> 
    <directors> 
     <director>Francis Ford Coppola</director> 
    </directors> 
    <genres> 
     <genre>Crime</genre> 
     <genre>Drama</genre> 
    </genres> 
    <plot>Son of a mafia boss takes over when his father is critically wounded in a mob hit.</plot> 
    <cast> 
     <performer> 
      <actor>Marlon Brando</actor> 
      <role>Don Vito Corleone</role> 
     </performer> 
     <performer> 
      <actor>Al Pacino</actor> 
      <role>Michael Corleone</role> 
     </performer> 
     <performer> 
      <actor>Diane Keaton</actor> 
      <role>Kay Adams Corleone</role> 
     </performer> 
     <performer> 
      <actor>Robert Duvall</actor> 
      <role>Tom Hagen</role> 
     </performer> 
     <performer> 
      <actor>James Caan</actor> 
      <role>Sonny Corleone</role> 
     </performer> 
    </cast> 
</film> 

Java類:

pa 

ckage Film; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathExpressionException; 
import javax.xml.xpath.XPathFactory; 

import org.w3c.dom.Document; 
import org.xml.sax.SAXException; 

public class ASS2_FILM{ 
    public static void main(String[] args) { 

     try { 
      FileInputStream file = new FileInputStream (new File("/Users/benchalmers/Documents/Uni /Year 2/Database Engineering/Assignment 3/Film/FILM.xml")); 

      DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 

      DocumentBuilder builder = builderFactory.newDocumentBuilder(); 

      Document xmlDocument = builder.parse(file); 

      XPath xPath = XPathFactory.newInstance().newXPath(); 

String expression3 = "/film/cast/"; 
      System.out.println(expression3); 
      String actor = xPath.compile(expression3).evaluate(xmlDocument); 
      System.out.println(actor); 

返回值:

/film/cast 


      Marlon Brando 
      Don Vito Corleone 


      Al Pacino 
      Michael Corleone 


      Diane Keaton 
      Kay Adams Corleone 


      Robert Duvall 
      Tom Hagen 


      James Caan 
      Sonny Corleone 

回答

1

爲了讓演員的名字只是嘗試從改變:

String expression3 = "/film/cast/"; 

收件人:

String expression3 = "/film/cast/performer/actor";