views:

319

answers:

1

Let's say I have this sample:

  page = "<html><body><h1 class='foo'></h1><p class='foo'>hello people<a href='http://'&gt;hello world</a></p></body></html>"
    @nodes = []
    Nokogiri::HTML(page).traverse do |n|
       if n[:class]  == "foo"
          @nodes << {:name => n.name, :xpath => n.path, :text => n.text }
       end
    end

the results would for the n.text would be hello peoplehello world, I want to do it in a way so I can get the parent text and its childs text, but relate them to their tag

so the result would be something like

@nodes[0][:text]=""
@node[1][:text]= [{:Elementtext1 => "hello people", :ElementObject1 => elementObject},{:Elementtext2 => "hello world", :ElementObject2 => elementObject}]
A: 

There we go

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::HTML(DATA.read)

nodes = doc.root.css('.foo').collect do |n|
  { :name => n.name,
    :xpath => n.path,
    :text => n.xpath('.//text()').collect{|t|
      { :parent => t.parent.name,
        :text => t.text }}}
end

p nodes

__END__
<html>
<body>
<h1 class='foo'></h1>
<p class='foo'>hello people<a href='http://'&gt;hello world</a></p>
</body>
</html>

you cannot reach all elements using traverse since it visits only the direct children of the root. Hence, I use a css selector to get all elements with class foo. And then, for each found element, I use an xpath selector to get all text nodes below it.

Adrian
many thanks adrian
Waheedi