diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index aaf9af9..cbe8966 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -55,6 +55,21 @@ module Oga return children.text end + ## + # Returns the text of the current element only. + # + # @return [String] + # + def inner_text + text = '' + + children.each do |child| + text << child.text if child.is_a?(Text) + end + + return text + end + ## # Converts the element and its child elements to XML. # diff --git a/spec/oga/xml/element_spec.rb b/spec/oga/xml/element_spec.rb index b6d60f0..5f34a94 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -46,6 +46,24 @@ describe Oga::XML::Element do end end + context '#inner_text' do + before do + t1 = Oga::XML::Text.new(:text => 'Foo') + t2 = Oga::XML::Text.new(:text => 'Bar') + + @n1 = described_class.new(:children => [t1]) + @n2 = described_class.new(:children => [@n1, t2]) + end + + example 'return the inner text of the parent node' do + @n2.inner_text.should == 'Bar' + end + + example 'return the inner text of the child node' do + @n1.inner_text.should == 'Foo' + end + end + context '#to_xml' do example 'generate the corresponding XML' do described_class.new(:name => 'p').to_xml.should == '

'