rails write xml with builder in action

两盒软妹~` 提交于 2019-12-06 05:27:18

Assuming the XML data is sitting in an ActiveRecord object then calling to_xml will give you the xml representation of the object. You can use Ruby's Net:HTTP module to handle the post.

http = Net::HTTP.new("www.thewebservicedomain.com")
response = http.post("/some/path/here", your_model_object.to_xml)

If you want to generate your XML inside your controller (not very Rails-like but you can still do it) use the builder gem:

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)

The second example produces the following XML string and HTTP POST's it to the destination server:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!