用Java查询XML

时间:2016-04-09 11:48:10

标签: java xml xpath netbeans

我能够使用Java在我的XML文档上运行简单查询,但我希望运行一个更高级的'查询并在这样做时遇到一些麻烦。

当我想获取XML文件中其余actor的名字时,我能够得到这个例子的第一个演员的名字(在本例中是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 个答案:

答案 0 :(得分:1)

要获取演员姓名,请尝试更改:

String expression3 = "/film/cast/";

致:

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