tags:

views:

261

answers:

1

using nokogiri,

i want to find <p class="main"> Some text here...</p>

from an html document,

and then output the location as below or something that shows the tree

html > body > div class = "body" > p class= "main "
+2  A: 
text="<html><body><div class='body'><p class='main'>some text here</p></div></body></html>"
doc = Nokogiri::HTML(text)
root = doc.root
node = doc.xpath('//p[@class="main"]').first
path = [node]
begin
  node = node.parent
  path.unshift node
end until node == root
path.map {|n| n.name}.join " > "

Exercise for you to add whichever attributes you want.

glenn jackman
can I add a question here? Suppose I want to display the path of all <p> tags and not just the first, how do I do it?
Vijay Dev
@Vijay, probably better to ask a new question, and reference this question if you want.
glenn jackman