-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathxpath.rb
79 lines (72 loc) · 1.75 KB
/
xpath.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
module OAI
module XPath
# get all matching nodes
def xpath_all(doc, path)
case parser_type(doc)
when 'libxml'
return doc.find(path).to_a if doc.find(path)
when 'rexml'
return REXML::XPath.match(doc, path)
end
return []
end
# get first matching node
def xpath_first(doc, path)
elements = xpath_all(doc, path)
return elements[0] if elements != nil
return nil
end
# get text for first matching node
def xpath(doc, path)
el = xpath_first(doc, path)
get_text el
end
def get_text(node)
return unless node
case parser_type(node)
when 'libxml'
return node.content
when 'rexml'
return node.text
end
return nil
end
# figure out an attribute
def get_attribute(node, attr_name)
case node.class.to_s
when 'REXML::Element'
return node.attribute(attr_name)
when 'LibXML::XML::Node'
#There has been a method shift between 0.5 and 0.7
if defined?(node.property) == nil
return node.attributes[attr_name]
else
#node.property is being deprecated. We'll eventually remove
#this trap
begin
return node[attr_name]
rescue
return node.property(attr_name)
end
end
end
return nil
end
private
# figure out what sort of object we should do xpath on
def parser_type(x)
case x.class.to_s
when 'LibXML::XML::Document'
return 'libxml'
when 'LibXML::XML::Node'
return 'libxml'
when 'LibXML::XML::Node::Set'
return 'libxml'
when 'REXML::Element'
return 'rexml'
when 'REXML::Document'
return 'rexml'
end
end
end
end