2011-03-10 102 views
0

從Ruby中的XML文檔生成查詢字符串(url params)的最佳選擇是什麼?xml查詢字符串

xml_string = <abc><session>1234</session><description>some_description</description></abc> 

query_string = # I want here "?abc=session......." 
+1

不應該是'?session = 1234&description = some_description'? URL參數是平坦的,例如,只有一個級別,而你的XML有兩個級別。 – gnab 2011-03-10 12:56:36

+0

你使用rails或active_support? – tokland 2011-03-10 13:11:20

回答

2
xml_string = "<abc><session>1234</session><description>some_description</description></abc>" 
result = "?"+Hash.from_xml(xml_string).to_query 
0

XmlSimple是一個很好的寶石。

require 'rubygems' 
require 'xmlsimple' 

data = XmlSimple.xml_in(xml_string) 
url_params = xml_to_url_params(data, "abc") 


def xml_to_url_params(xml_data, root) 
    elements = [] 
    data[root].each do |item| 
    item.each do |name, value| 
     elements << "#{CGI::escape(name)}=#{CGI::escape(value)}" 
    end 
    end 
    elements.join("&") 
end 

ps。沒有測試過這個代碼,所以可能會有bug;)