1

I am trying to get the sum of a column in an html table. The first row of this table is all titles. Every cell of every row past the first has the class "right", so I was going to use that class as a selector to ignore the unnecessary titles. However, I only need the second cell of each row. How do I combine these two selectors? Is this right?

my $tree = HTML::TreeBuilder::XPath->new_from_file($fileName);
foreach $value ($tree->findnodes('//table/tr/td[@class="right"[position()=2]')){
    stuff;
}
user2933738
  • 75
  • 1
  • 1
  • 9
  • There are two left square brackets, but only one right square bracket. It is probably not right. – choroba Mar 10 '14 at 16:33

1 Answers1

2

You can combine the predicates by just putting one after another:

//table/tr/td[@class="right"][2]

or, you can use the logical and

//table/tr/td[@class="right" and position()=2]
choroba
  • 231,213
  • 25
  • 204
  • 289
  • So this would be correct for adding the value of each of these cells? foreach $val ($tree->findnodes('//table/tr/td[@class="right"][2])){ $sum += $val->findvalue(); } – user2933738 Mar 10 '14 at 16:48
  • If you just want to sum, you can use XPath function sum(): `sum(//table/tr/td[@class="right"][2])` – choroba Mar 10 '14 at 16:53
  • Hold on--would using this notation give me all cells that are second children, or would it give me the second children of cells? – user2933738 Mar 10 '14 at 16:56
  • @user2933738: `[position()=2]` and `[2]` mean the same in XPath. `parent/element[2]` returns the second `element` child of `parent`. To get the second child of `element`, you would need `parent/element/*[2]`. – choroba Mar 10 '14 at 17:13
  • Okay. So, in order to get the "right" class, second child of , I would say this? findnodes('//table/tr[2][@class="right"]') Or would that get me the second child of of "right" class tr objects? – user2933738 Mar 10 '14 at 18:18
  • @user2933738: No, check the documentation and my answer. – choroba Mar 10 '14 at 20:38