XML module for more easily querying using XPath.

This commit is contained in:
Yorick Peterse 2014-09-02 20:16:52 +02:00
parent ad34ab47a0
commit 9649b50cc9
5 changed files with 72 additions and 0 deletions

View File

@ -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'

View File

@ -13,6 +13,8 @@ module Oga
# @return [Oga::XML::XmlDeclaration]
#
class Document
include Querying
attr_accessor :doctype, :xml_declaration
##

View File

@ -21,6 +21,8 @@ module Oga
# @return [Hash]
#
class Element < Node
include Querying
attr_accessor :name, :namespace_name, :attributes, :namespaces
##

32
lib/oga/xml/querying.rb Normal file
View File

@ -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

View File

@ -0,0 +1,35 @@
require 'spec_helper'
describe Oga::XML::Querying do
before do
@document = parse('<a>foo</a>')
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