假設XML數據是坐在一個ActiveRecord對象,然後調用to_xml會給你對象的XML表示。您可以使用Ruby的Net:HTTP模塊來處理帖子。
http = Net::HTTP.new("www.thewebservicedomain.com")
response = http.post("/some/path/here", your_model_object.to_xml)
如果你想生成您的控制器內部的XML(不是很Rails的一樣,但你仍然可以做到這一點),用建設者的寶石:
xml = Builder::XmlMarkup.new
xml.instruct! :xml, :verison => "1.0" # Or whatever your requirements are
# Consult the Builder gem docs for different ways you can build up your XML, this is just a simple example.
xml.widgets do
xml.widget do
xml.serial_number("12345")
xml.name("First Widget")
xml.any_other_tag_you_need("Contents of tag")
end
end
# And now send the request
http = Net::HTTP.new("www.thewebservicedomain.com")
response = http.post("/some/path/here", xml)
第二個例子產生下面的XML字符串和HTTP POST將其發送到目標服務器:
<inspect/><?xml version=\"1.0\" encoding=\"UTF-8\" verison=\"1.0\"?><widgets><widget><serial_number>12345</serial_number><name>First Widget</name><any_other_tag_you_need>Contents of tag</any_other_tag_you_need></widget></widgets>
對不起。我不明白。爲什麼我將xml保存在ActiveRecord對象中。我只想創建一個xml,然後通過發佈發送。現在我編輯我的帖子並寫一個例子。謝謝 – maxiperez 2011-04-19 17:54:41
再次抱歉。該XML有其他信息和標籤。我必須遵循hipay documentation的xml feed。因此我必須在xml中創建其他標籤。 – maxiperez 2011-04-19 18:47:41
@maxiperez我提供的示例不保存ActiveRecord中的任何xml,它將ActiveRecord對象轉換爲表示對象內容的xml字符串。這是一個常見的Rails成語。我會在幾分鐘內重寫我的答案,並沿着你所尋找的內容向你舉一個例子。 – MDaubs 2011-04-20 17:46:51