鋸山

2017-07-19 19 views
1

で指定された名前を持つ単一の子要素を取得するのは、私はこのような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')のようなものが理想的です。

+1

知っている場合は、[このチュートリアル](http://www.nokogiri.org/tutorials/searching_a_xml_html_document.html)を見たことがありますか? 「ノコギリは名前で要素を見つけよう」とグーグルで見つけた – alexanderbird

答えて

3

xpathで試してください。

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

か、あなただけの1

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

おかげで、「.at_xpath」はまさに私が探していたものでした。 – Jones

+1

FWIWでは、CSSスタイルのセレクタを使用することもできます(例えば 'doc.css( '結論')'や 'doc.at_css( '結論')')。 – orde

+0

ありがとう – Ursus

関連する問題