开发者

Xpath: Selecting all of an element type?

I'm just starting to learn Xpath, I'm trying to write a line of code that will select all of the actors in EACH movie parent (through Java!). Below, I have an example of one movie, but there are multiple <Movie&开发者_高级运维gt; elements, each with <Actor> elements.

<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>

Currently, I can only select the first <Actor> element of each <Movie> element -- is it possible to select all of them without using a for loop?

Here is my current line of code that displays the first <Actor> element of every <Movie> element:

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

Any and all help if much appreciated!


No, you need a for loop to iterate over each Node in a NodeList returned by the evaluate method.

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: Good movie btw :-).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜