Xpath:选择所有元素类型?

时间:2011-01-31 23:22:24

标签: java xml xpath

我刚刚开始学习Xpath,我正在尝试编写一行代码来选择EACH电影父母中的所有演员(通过Java!)。下面,我有一个电影的示例,但有多个<Movie>元素,每个元素都有<Actor>元素。

<Movie Genre = 'Other'>
    <Title>Requiem For A Dream</Title>
    <ReleaseYear>2000</ReleaseYear>
    <Director>Darren Aronofsky</Director>
    <Actor Character = 'Sara Goldfarb'>Ellen Burstyn</Actor>
    <Actor Character = 'Harry Goldfarb'>Jared Leto</Actor>
    <Actor Character = 'Marion Silver'>Jennifer Connelly</Actor>
    <Actor Character = 'Tyrone C. Love'>Marlon Wayans</Actor>
</Movie>

目前,我只能选择每个<Actor>元素的第一个<Movie>元素 - 是否可以在不使用for循环的情况下选择所有元素?

以下是我当前的代码行,它显示了每个<Actor>元素的第一个<Movie>元素:

System.out.println("Starring: " + xpath.evaluate("Actor", movieNode) + " as " + xpath.evaluate("Actor/@Character", movieNode) + "\n");

如果非常感谢,请提供任何帮助!

1 个答案:

答案 0 :(得分:4)

不,您需要一个for循环来迭代Node方法返回的NodeList中的每个evaluate

NodeList nodes = (NodeList)xpath.evaluate("Actor", movieNode, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
  Element actor = (Element)nodes.item(i);
  String actorName = actor.getTextContent();
  String character = actor.getAttribute("Character");
  System.out.println("Starring: " + actorName + " as " + character + "\n");
}

PS:好电影顺便说一句: - )。