Deepti Kakade
Deepti Kakade

Reputation: 3203

How to get parent's text using Nokogiri

I have situation where I want to get a parent <p> tag's text. For example:

<p>
  <a name="TOPIC"></a>
  <b><font color="#800000" size="4" face="Arial">Exapmles</font></b>
</p>

This is working fine for this example:

test = Nokogiri::HTML("row['test']"])
raw_attributes = test.root.css("p a").inject({}) do |accumulator, element| 
  accumulator[element.attr("name")] = (element.parent.text).strip
  accumulator
end

But it's not working for the following example:

<p>
  <font>
    <a name="TOPIC"></a>
    <b><font color="#800000" size="4" face="Arial">Exapmles</font></b>
  </font>
</p>

How can I do this using Nokogiri? I want the solution which works for both of the above two conditions.

Upvotes: 0

Views: 251

Answers (1)

Phrogz
Phrogz

Reputation: 303188

puts doc.at_xpath("//p[//a[@name='TOPIC']]").inner_text.strip
#=> "Exapmles"

Decoded, this says:

  • //p — find a p element anywhere in the document
    • […] — that matches this condition
    • //a — it has an a element as a descendant
      • [@name='TOPIC'] — with a name attribute whose value is TOPIC.

Upvotes: 2

Related Questions