Rails在运行中使用builder编写xml [英] rails write xml with builder in action
问题描述
我想在我的网站上使用hipay。所以我需要在一个动作中生成一个xml,然后通过邮寄发送到hipay网站。
I want to use hipay in my site. So i need generate a xml in a action and then send via post to hipay site.
我的问题是:
如何动态创建xml,然后在同一操作中通过邮寄发送此xml?
How i can create a xml dinamically and then , in the same action, send this xml via post?
控制器中的示例
def action_generate_xml
@xml = Builder::XmlMarkup.new()
# I want generate my xml here
#
#
# End generate xml
#Now i want send My XML via post
#CODE FOR SEND VIA POST
end
预先感谢
推荐答案
假定XML数据位于ActiveRecord对象中,则调用to_xml将为您提供该对象的xml表示形式。您可以使用Ruby的Net:HTTP模块来处理该帖子。
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)
如果您想在控制器内部生成XML(不是很像Rails,但您仍然可以做到),请使用构建器gem:
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)
第二个示例产生以下XML字符串和HTTP POST将其发送到目标服务器:
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>
这篇关于Rails在运行中使用builder编写xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!