diff --git a/lib/oga.rb b/lib/oga.rb index 83537c7..bfdc401 100644 --- a/lib/oga.rb +++ b/lib/oga.rb @@ -16,6 +16,7 @@ if RUBY_PLATFORM == 'java' end #:nocov: +require_relative 'oga/xml/querying' require_relative 'oga/xml/node' require_relative 'oga/xml/document' require_relative 'oga/xml/character_node' diff --git a/lib/oga/xml/document.rb b/lib/oga/xml/document.rb index ae82630..2c9fb33 100644 --- a/lib/oga/xml/document.rb +++ b/lib/oga/xml/document.rb @@ -13,6 +13,8 @@ module Oga # @return [Oga::XML::XmlDeclaration] # class Document + include Querying + attr_accessor :doctype, :xml_declaration ## diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index 70154ca..4947f98 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -21,6 +21,8 @@ module Oga # @return [Hash] # class Element < Node + include Querying + attr_accessor :name, :namespace_name, :attributes, :namespaces ## diff --git a/lib/oga/xml/querying.rb b/lib/oga/xml/querying.rb new file mode 100644 index 0000000..6c2fb10 --- /dev/null +++ b/lib/oga/xml/querying.rb @@ -0,0 +1,32 @@ +module Oga + module XML + ## + # The Querying module provides methods that make it easy to run XPath/CSS + # queries on XML documents/elements. + # + module Querying + ## + # Evaluates the given XPath expression. + # + # @param [String] expression The XPath expression to run. + # @param [Hash] variables Variables to bind. + # @see [Oga::XPath::Evaluator#initialize] + # + def xpath(expression, variables = {}) + return XPath::Evaluator.new(self, variables).evaluate(expression) + end + + ## + # Evaluates the given XPath expression and returns the first node in the + # set. + # + # @see [#xpath] + # + def at_xpath(*args) + result = xpath(*args) + + return result.is_a?(XML::NodeSet) ? result.first : result + end + end # Querying + end # XML +end # Oga diff --git a/spec/oga/xml/querying_spec.rb b/spec/oga/xml/querying_spec.rb new file mode 100644 index 0000000..a50f38d --- /dev/null +++ b/spec/oga/xml/querying_spec.rb @@ -0,0 +1,35 @@ +require 'spec_helper' + +describe Oga::XML::Querying do + before do + @document = parse('foo') + end + + context '#xpath' do + example 'query a document' do + @document.xpath('a')[0].name.should == 'a' + end + + example 'query an element' do + @document.children[0].xpath('text()')[0].text.should == 'foo' + end + + example 'evaluate an expression using a variable' do + @document.xpath('$number', 'number' => 10).should == 10 + end + end + + context '#at_xpath' do + example 'query a document' do + @document.at_xpath('a').name.should == 'a' + end + + example 'query an element' do + @document.children[0].at_xpath('text()').text.should == 'foo' + end + + example 'evaluate an expression using a variable' do + @document.at_xpath('$number', 'number' => 10).should == 10 + end + end +end