1

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.

4

1 回答 1

1

假设您的 HTML 与上一个问题相同:

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

然后你可以这样做:

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
于 2012-12-01T02:17:28.467 回答