使用 Nokogiri 获取具有给定名称的单个子元素

Getting a single child element with a given name with Nokogiri

假设我有 XML,它看起来像这样:

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

有没有一种方法可以让我得到 conclusion,而不用像这样的丑陋循环:

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

puts conclusion

最好是 python 的 Element.find('conclusion')

尝试使用 xpath 方法。

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

或者,如果你知道只有一个

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