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]


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

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]


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

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:



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)

Parameters:

  • expression (String)

    The XPath expression to run.

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

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

  • namespaces (Hash)

    Namespace aliases. The keys of this Hash should be String values.

Returns:



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