Support for the XPath namespace-uri() function.

This commit is contained in:
Yorick Peterse 2014-08-21 19:02:41 +02:00
parent 9e20b5ca3e
commit 8cc0db2283
2 changed files with 85 additions and 11 deletions

View File

@ -706,21 +706,33 @@ module Oga
# @return [Oga::XML::NodeSet]
#
def on_call_local_name(context, expression = nil)
if expression
node = process(expression, context)
if node.is_a?(XML::NodeSet)
node = node.first
else
raise TypeError, 'local-name() only takes node sets as arguments'
end
else
node = current_node
end
node = context_node(context, expression)
return node.is_a?(XML::Element) ? node.name : ''
end
##
# Processes the `namespace-uri()` function call.
#
# This function call returns the namespace URI of one of the following:
#
# * The current context node (if any)
# * The first node in the supplied node set
#
# @param [Oga::XML::NodeSet] context
# @param [Oga::XPath::Node] expression
# @return [Oga::XML::NodeSet]
#
def on_call_namespace_uri(context, expression = nil)
node = context_node(context, expression)
if node.is_a?(XML::Element) and node.namespace
return node.namespace.uri
else
return ''
end
end
##
# Processes an `(int)` node. This method simply returns the value as a
# Float.
@ -744,6 +756,30 @@ module Oga
return ast_node.children[0]
end
##
# Returns the node for a function call. This node is either the first node
# in the supplied node set, or the first node in the current context.
#
# @param [Oga::XML::NodeSet] context
# @param [Oga::XPath::Node] expression
# @return [Oga::XML::Node]
#
def context_node(context, expression = nil)
if expression
node = process(expression, context)
if node.is_a?(XML::NodeSet)
node = node.first
else
raise TypeError, 'only node sets can be used as arguments'
end
else
node = current_node
end
return node
end
##
# Returns a node set containing all the child nodes of the given set of
# nodes.

View File

@ -0,0 +1,38 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'namespace-uri() function' do
before do
@document = parse('<root xmlns:x="y"><x:a></x:a><b></b></root>')
@evaluator = described_class.new(@document)
end
context 'outside predicates' do
example 'return the namespace URI of the <x:a> node' do
@evaluator.evaluate('namespace-uri(root/x:a)').should == 'y'
end
example 'return an empty string when there is no namespace URI' do
@evaluator.evaluate('namespace-uri(root/b)').should == ''
end
example 'raise TypeError for invalid argument types' do
block = lambda { @evaluator.evaluate('namespace-uri("foo")') }
block.should raise_error(TypeError)
end
end
context 'inside predicates' do
before do
@set = @evaluator.evaluate('root/*[namespace-uri()]')
end
it_behaves_like :node_set, :length => 1
example 'return the <x:a> node' do
@set[0].should == @document.children[0].children[0]
end
end
end
end