问题
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.
My question is:
How i can create a xml dinamically and then , in the same action, send this xml via post?
Example in my controller
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
Thanks in advance
回答1:
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>
来源:https://stackoverflow.com/questions/5719634/rails-write-xml-with-builder-in-action