Reputation: 11
I'm able to run simple queries on my XML document using Java, but I'm looking to run a more 'advanced' query and have run into a bit of trouble in doing so.
I am able to get the name of only the first actor of this example (in this case Marlon Brando), when I want to get the names of the rest of the actors in the XML file.
I have used so far /film/cast
which shows me all of the actor names, but also the role they play within the film; which I do not want.
Please help! Thanks
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 class:
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);
Returned value:
/film/cast
Marlon Brando
Don Vito Corleone
Al Pacino
Michael Corleone
Diane Keaton
Kay Adams Corleone
Robert Duvall
Tom Hagen
James Caan
Sonny Corleone
Upvotes: 1
Views: 522
Reputation: 9627
To get actor names only try to change from:
String expression3 = "/film/cast/";
To:
String expression3 = "/film/cast/performer/actor";
Upvotes: 1