diff --git a/lib/rexml/xpath_parser.rb b/lib/rexml/xpath_parser.rb index d8b88e7..5eb1e5a 100644 --- a/lib/rexml/xpath_parser.rb +++ b/lib/rexml/xpath_parser.rb @@ -590,6 +590,7 @@ def filter_nodeset(nodeset) def evaluate_predicate(expression, nodesets) enter(:predicate, expression, nodesets) if @debug + new_nodeset_count = 0 new_nodesets = nodesets.collect do |nodeset| new_nodeset = [] subcontext = { :size => nodeset.size } @@ -606,17 +607,20 @@ def evaluate_predicate(expression, nodesets) result = result[0] if result.kind_of? Array and result.length == 1 if result.kind_of? Numeric if result == node.position - new_nodeset << XPathNode.new(node, position: new_nodeset.size + 1) + new_nodeset_count += 1 + new_nodeset << XPathNode.new(node, position: new_nodeset_count) end elsif result.instance_of? Array if result.size > 0 and result.inject(false) {|k,s| s or k} if result.size > 0 - new_nodeset << XPathNode.new(node, position: new_nodeset.size + 1) + new_nodeset_count += 1 + new_nodeset << XPathNode.new(node, position: new_nodeset_count) end end else if result - new_nodeset << XPathNode.new(node, position: new_nodeset.size + 1) + new_nodeset_count += 1 + new_nodeset << XPathNode.new(node, position: new_nodeset_count) end end end diff --git a/test/xpath/test_base.rb b/test/xpath/test_base.rb index 5156bbb..68b33ab 100644 --- a/test/xpath/test_base.rb +++ b/test/xpath/test_base.rb @@ -451,6 +451,46 @@ def test_following # puts results #end + def test_nested_predicates + doc = Document.new <<-EOF +
+
+ ab + cd +
+
+ ef + gh +
+
+ hi +
+
+ EOF + + matches = XPath.match(doc, '(/div/div/test[0])').map(&:text) + assert_equal [], matches + matches = XPath.match(doc, '(/div/div/test[1])').map(&:text) + assert_equal ["ab", "ef", "hi"], matches + matches = XPath.match(doc, '(/div/div/test[2])').map(&:text) + assert_equal ["cd", "gh"], matches + matches = XPath.match(doc, '(/div/div/test[3])').map(&:text) + assert_equal [], matches + + matches = XPath.match(doc, '(/div/div/test[1])[1]').map(&:text) + assert_equal ["ab"], matches + matches = XPath.match(doc, '(/div/div/test[1])[2]').map(&:text) + assert_equal ["ef"], matches + matches = XPath.match(doc, '(/div/div/test[1])[3]').map(&:text) + assert_equal ["hi"], matches + matches = XPath.match(doc, '(/div/div/test[2])[1]').map(&:text) + assert_equal ["cd"], matches + matches = XPath.match(doc, '(/div/div/test[2])[2]').map(&:text) + assert_equal ["gh"], matches + matches = XPath.match(doc, '(/div/div/test[2])[3]').map(&:text) + assert_equal [], matches + end + # Contributed by Mike Stok def test_starts_with source = <<-EOF