2011-07-01 37 views
0

我有一個從Web服務響應創建的常規xml對象。如何在Ruby中導航XML對象

我需要從一些特定的按鍵得到一些特定值...例如:

<tag> 
<tag2> 
    <tag3> 
    <needThisValue>3</needThisValue> 
    <tag4> 
    <needThisValue2>some text</needThisValue2> 
    </tag4> 
    </tag3> 
</tag2> 
</tag> 

我怎樣才能在Ruby中<needThisValue><needThisValue2>

+0

你確定這是你想要的嗎?你的意思是' 3'和'一些文本'?或者,你的意思是'3'和'一些文字'? – sawa

回答

5

我的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。它非常強大,使用起來非常簡單。

2
require "rexml/document" 
include REXML 
doc = Document.new string 
puts XPath.first(doc, "//tag/tag2/tag3/needThisValue").text 
puts XPath.first(doc, "//tag/tag2/tag3/tag4/needThisValue2").text