Take the 2-minute tour ×

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 "
share|improve this question

1 Answer 1

up vote 2 down vote accepted
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]
  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.

share|improve this answer
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 Jul 17 '10 at 20:37
@Vijay, probably better to ask a new question, and reference this question if you want. –  glenn jackman Jul 19 '10 at 13:28

Your Answer


