Module: Oga::XML::Querying

Included in:
Document, Element
Defined in:
lib/oga/xml/querying.rb

Overview

The Querying module provides methods that make it easy to run XPath/CSS queries on XML documents/elements.

Instance Method Summary collapse

Instance Method Details

#at_css(*args) ⇒ Oga::XML::Node|Oga::XML::Attribute

Evaluates the CSS expression and returns the first matched node.

Returns:

See Also:

  • Oga::XML::Querying.[[#css]


88
89
90
91
92
# File 'lib/oga/xml/querying.rb', line 88

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

Evaluates the XPath expression and returns the first matched node.

Querying a document:

document = Oga.parse_xml <<-EOF
<people>
  <person age="25">Alice</person>
</people>
EOF

person = document.at_xpath('people/person')

person.class # => Oga::XML::Element

Returns:

See Also:

  • Oga::XML::Querying.[[#xpath]


57
58
59
60
61
# File 'lib/oga/xml/querying.rb', line 57

def at_xpath(*args)
  result = xpath(*args)

  result.is_a?(XML::NodeSet) ? result.first : result
end

#css(expression) ⇒ Oga::XML::NodeSet

Evaluates the given CSS expression.

Querying a document:

document = Oga.parse_xml <<-EOF
<people>
  <person age="25">Alice</person>
</people>
EOF

document.css('people person')

Parameters:

  • expression (String)

    The CSS expression to run.

Returns:



77
78
79
80
81
82
# File 'lib/oga/xml/querying.rb', line 77

def css(expression)
  ast   = CSS::Parser.parse_with_cache(expression)
  block = XPath::Compiler.compile_with_cache(ast)

  block.call(self)
end

#xpath(expression, variables = {}) ⇒ Oga::XML::NodeSet

Evaluates the given XPath expression.

Querying a document:

document = Oga.parse_xml <<-EOF
<people>
  <person age="25">Alice</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)

Parameters:

  • expression (String)

    The XPath expression to run.

  • variables (Hash) (defaults to: {})

    Variables to bind. The keys of this Hash should be String values.

Returns:



34
35
36
37
38
39
# File 'lib/oga/xml/querying.rb', line 34

def xpath(expression, variables = {})
  ast   = XPath::Parser.parse_with_cache(expression)
  block = XPath::Compiler.compile_with_cache(ast)

  block.call(self, variables)
end