我的Nokogiri大風扇:
xml = <<EOT
<tag>
<tag2>
<tag3>
<needThisValue>3</needThisValue>
<tag4>
<needThisValue2>some text</needThisValue2>
</tag4>
</tag3>
</tag2>
</tag>
EOT
這對於解析創建一個文檔:
require 'nokogiri'
doc = Nokogiri::XML(xml)
使用at
找到匹配的存取的第一個節點:
doc.at('needThisValue2').class # => Nokogiri::XML::Element
或search
查找與訪問器匹配的所有節點作爲節點集,其作用就像陣列:
doc.search('needThisValue2').class # => Nokogiri::XML::NodeSet
doc.search('needThisValue2')[0].class # => Nokogiri::XML::Element
此使用CSS存取來定位每一個節點的第一個實例:與節點集使用CSS
doc.at('needThisValue').text # => "3"
doc.at('needThisValue2').text # => "some text"
再次:
doc.search('needThisValue')[0].text # => "3"
doc.search('needThisValue2')[0].text # => "some text"
如果需要,可以使用XPath訪問器而不是CSS:
doc.at('//needThisValue').text # => "3"
doc.search('//needThisValue2').first.text # => "some text"
通過the tutorials獲得Jumpstart。它非常強大,使用起來非常簡單。
你確定這是你想要的嗎?你的意思是' 3 needThisValue>'和'一些文本 needThisValue2>'?或者,你的意思是'3'和'一些文字'? –
sawa