Ben
Ben

Reputation: 53

Return nth child

Using the following statement I get a valis response for i = 1 but when trying i = 2 etc I get an array out of bounds exception, any pointers would be great!

AutoPilot resultNode = new AutoPilot();
resultNode.selectXPath("/top/level[@sev='4']/item/title/text()[i]");
resultNode.bind(vn);
int z = resultNode.evalXPath();
System.out.println("TEST: "+vn.toString(z));

Example XML:

<top>
  <level sev="4">
    <item>
      <title>gngsfjdsf</title>
      <p1>2</p1>
      <p2>2</p2>
    </item>
    <item>
      <title>sdadad</title>
      <p1>2</p1>
      <p2>2</p2>
    </item>
  </level>
  <level sev="3">
    <item>
      <title>3214125421</title>
      <p1>2</p1>
      <p2>1</p2>
    </item>
    <item>
      <title>kjhkjtnjy</title>
      <p1>1</p1>
      <p2>2</p2>
    </item>
  </level>
</top>

Upvotes: 1

Views: 148

Answers (2)

vtd-xml-author
vtd-xml-author

Reputation: 3377

you dont have a second text node for title element. so evalXPath() should return a -1 which is supposed to throw an out of bound exception.

Upvotes: 1

Petr Janeček
Petr Janeček

Reputation: 38424

This:

/top/level[@sev='4']/item/title/text()

indeed returns two values:

gngsfjdsf
sdadad

So you need to select only the second one, and you can do it by using parentheses:

(/top/level[@sev='4']/item/title/text())[2]

returns only

sdadad

The reason for your failure is that .../text()[2] tries to find the second text node of each of the found nodes, not the overall second node.


An even better solution is to select the second item node instead of trying to only get the second text() node of all the matched nodes...

/top/level[@sev='4']/item[2]/title/text()

Upvotes: 3

Related Questions