Module: Oga::XML::Querying
Overview
The Querying module provides methods that make it easy to run XPath/CSS queries on XML documents/elements.
Instance Method Summary collapse
-
#at_css(*args) ⇒ Oga::XML::Node|Oga::XML::Attribute
Evaluates the CSS expression and returns the first matched node.
-
#at_xpath(*args) ⇒ Oga::XML::Node|Oga::XML::Attribute
Evaluates the XPath expression and returns the first matched node.
-
#css(expression) ⇒ Oga::XML::NodeSet
Evaluates the given CSS expression.
-
#xpath(expression, variables = {}, namespaces: nil) ⇒ Oga::XML::NodeSet
Evaluates the given XPath expression.
Instance Method Details
#at_css(*args) ⇒ Oga::XML::Node|Oga::XML::Attribute
Evaluates the CSS expression and returns the first matched node.
97 98 99 100 101 |
# File 'lib/oga/xml/querying.rb', line 97 def at_css(*args) result = css(*args) result.is_a?(XML::NodeSet) ? result.first : result end |
#at_xpath(*args) ⇒ Oga::XML::Node|Oga::XML::Attribute
66 67 68 69 70 |
# File 'lib/oga/xml/querying.rb', line 66 def at_xpath(*args) result = xpath(*args) result.is_a?(XML::NodeSet) ? result.first : result end |
#css(expression) ⇒ Oga::XML::NodeSet
86 87 88 89 90 91 |
# File 'lib/oga/xml/querying.rb', line 86 def css(expression) ast = CSS::Parser.parse_with_cache(expression) block = XPath::Compiler.compile_with_cache(ast) block.call(self) end |
#xpath(expression, variables = {}, namespaces: nil) ⇒ Oga::XML::NodeSet
Evaluates the given XPath expression.
Querying a document:
document = Oga.parse_xml <<-EOF
<people>
<person age="25">Alice</person>
<ns:person xmlns:ns="http://example.net">Bob</ns:person>
</people>
EOF
document.xpath('people/person')
Querying an element:
element = document.at_xpath('people')
element.xpath('person')
Using variable bindings:
document.xpath('people/person[@age = $age]', 'age' => 25)
Using namespace aliases:
namespaces = {'example' => 'http://example.net'}
document.xpath('people/example:person', namespaces: namespaces)
43 44 45 46 47 48 |
# File 'lib/oga/xml/querying.rb', line 43 def xpath(expression, variables = {}, namespaces: nil) ast = XPath::Parser.parse_with_cache(expression) block = XPath::Compiler.compile_with_cache(ast, namespaces: namespaces) block.call(self, variables) end |