Jones
Jones

Reputation: 1214

Getting a single child element with a given name with Nokogiri

Let's say I have XML which looks like this:

<paper>
    <header>
    </header>
    <body>
        <paragraph>
        </paragraph>
    </body>
    <conclusion>
    </conclusion>
</paper>

Is there a way I can just get conclusion, without making an ugly loop like:

for child in paper.children do
    if child.name == "conclusion"
        conclusion = child
    end
end

puts conclusion

Ideally something like python's Element.find('conclusion').

Upvotes: 1

Views: 1033

Answers (1)

Ursus
Ursus

Reputation: 30056

Try with xpath method.

node = doc.xpath("//conclusion")[0]

or, if you know is just one

node = doc.at_xpath("//conclusion")

Upvotes: 4

Related Questions