Reputation: 266960
I'm using nokogiri and my object graph when looping looks like:
#<Nokogiri::XML::Element:0x3fe7b34a49c8 name="dt" children=[#
<Nokogiri::XML::Element:0x3fe7b34a4720 name="a" attributes=[#
<Nokogiri::XML::Attr:0x3fe7b34a46bc name="href" value="http://www.example.com">, #
<Nokogiri::XML::Attr:0x3fe7b34a4694 name="add_date" value="1246334352997870">] children=[#
<Nokogiri::XML::Text:0x3fe7b34a39c4 "Example.com Website ">]>, #
<Nokogiri::XML::Text:0x3fe7b34a35f0 "\n">,
I want to load this information into this class:
class LinkInfo
attr_accessor :href, :add_date, :text
end
href = http://www.example.com
add_date = 1246334352997870
text = "example.com website"
Is there an elegant way to do this, I'm currently looping through the children, and doing things with if statements to see if I am at the right tag name etc.
I know in ruby you can see if a value is in a collection using contains?, but I also want to then get the value of that.
Upvotes: 1
Views: 1014
Reputation: 37507
Assuming your HTML is identical to your last question:
<dl><p>
<dt><h3 ADD_DATE="120ssssss">label 1</H#>
</dl>
<dl><p>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 1</A>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 2</A>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 3</A>
</dl>
<dl><p>
<dt><h3 ADD_DATE="120ssssss">label 2</H#>
</dl>
<dl><p>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 1</A>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 2</A>
<dt><a href="http://www.example.com" ADD_DATE="12312323">Text 3</A>
</dl>
Then you can do this:
doc = Nokogiri.HTML(html)
links = doc.css('dl dt a').map do |link|
li = LinkInfo.new
li.href = link['href']
li.add_date = link['ADD_DATE']
li.text = link.text
li
end
Upvotes: 1