/
xpath_context.cr
73 lines (63 loc) · 1.85 KB
/
xpath_context.cr
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
class XML::XPathContext
def initialize(node : Node)
@ctx = LibXML.xmlXPathNewContext(node.to_unsafe.value.doc)
@ctx.value.node = node.to_unsafe
end
def evaluate(search_path : String)
xpath = LibXML.xmlXPathEvalExpression(search_path, self)
unless xpath
{% if flag?(:arm) || flag?(:aarch64) %}
if errors = XML::Error.errors
raise errors.last
end
{% end %}
raise XML::Error.new("Error in '#{search_path}' expression", 0)
end
raise XML::Error.new("Error in '#{search_path}' expression", 0) unless xpath.value
case xpath.value.type
when LibXML::XPathObjectType::STRING
String.new(xpath.value.stringval)
when LibXML::XPathObjectType::NUMBER
xpath.value.floatval
when LibXML::XPathObjectType::BOOLEAN
xpath.value.boolval != 0
when LibXML::XPathObjectType::NODESET
if xpath.value.nodesetval
NodeSet.new(Node.new(@ctx.value.doc), xpath.value.nodesetval)
else
NodeSet.new(Node.new(@ctx.value.doc))
end
else
NodeSet.new(Node.new(@ctx.value.doc))
end
end
def register_namespaces(namespaces) : Nil
namespaces.each do |prefix, uri|
register_namespace prefix, uri
end
end
def register_namespace(prefix : String, uri : String?)
prefix = prefix.lchop("xmlns:")
LibXML.xmlXPathRegisterNs(self, prefix, uri.to_s)
end
def register_variables(variables) : Nil
variables.each do |name, value|
register_variable name, value
end
end
def register_variable(name, value)
case value
when Bool
obj = LibXML.xmlXPathNewBoolean(value ? 1 : 0)
when Number
obj = LibXML.xmlXPathNewFloat(value.to_f64)
else
obj = LibXML.xmlXPathNewCString(value.to_s)
end
LibXML.xmlXPathRegisterVariable(self, name, obj)
end
def to_unsafe
@ctx
end
end
LibXML.xmlXPathInit