1 require 'rexml/functions'
2 require 'rexml/xpath_parser'
5 # Wrapper class. Use this class to access the XPath functions.
10 # Finds and returns the first node that matches the supplied xpath.
14 # The xpath to search for. If not supplied or nil, returns the first
17 # If supplied, a Hash which defines a namespace mapping.
20 # XPath.first( doc, "//b"} )
21 # XPath.first( node, "a/x:b", { "x"=>"http://doofus" } )
22 def XPath::first element, path=nil, namespaces=nil, variables={}
23 raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
24 raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
25 parser = XPathParser.new
26 parser.namespaces = namespaces
27 parser.variables = variables
28 path = "*" unless path
29 element = [element] unless element.kind_of? Array
30 parser.parse(path, element).flatten[0]
33 # Itterates over nodes that match the given path, calling the supplied
34 # block with the match.
38 # The xpath to search for. If not supplied or nil, defaults to '*'
40 # If supplied, a Hash which defines a namespace mapping
42 # XPath.each( node ) { |el| ... }
43 # XPath.each( node, '/*[@attr='v']' ) { |el| ... }
44 # XPath.each( node, 'ancestor::x' ) { |el| ... }
45 def XPath::each element, path=nil, namespaces=nil, variables={}, &block
46 raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
47 raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
48 parser = XPathParser.new
49 parser.namespaces = namespaces
50 parser.variables = variables
51 path = "*" unless path
52 element = [element] unless element.kind_of? Array
53 parser.parse(path, element).each( &block )
56 # Returns an array of nodes matching a given XPath.
57 def XPath::match element, path=nil, namespaces=nil, variables={}
58 parser = XPathParser.new
59 parser.namespaces = namespaces
60 parser.variables = variables
61 path = "*" unless path
62 element = [element] unless element.kind_of? Array
63 parser.parse(path,element)