I have a client that is sending XML for my site to parse. I am typically a PHP guy and understand how to parse it via PHP, but I am not sure how to do the same with Ruby. The client said they are going to post their XML file to my server (i.e. code below)
curl -X POST -H "Content-Type: text/xml" -d "@/path/to/file.xml" my-web-address.com/parser
and then the parser handler page needs to be able to detect that a file was sent to it, and parse it. Does this mean that Ruby simply looks for any POST request? What do I call to get the POST content (XML file) into a variable to mess with it?
I'm using Nokogiri to parse the XML.
doc = Nokogiri::XML(xml)
Appreciate any insight!
Simple solution without external gems:
class MyController < ApplicationController
def postxml
h = Hash.from_xml(request.body.read)
Rails.logger.info h
render status: 200
end
end
Note that you already get the XML contents in params
, as a hash. But if you stil prefer to use Nokogiri:
def some_action
doc = Nokogiri::XML(request.body.read) # or Nokogiri::XML.fragment
...
end
if you are using rails it should "decode" the xml POST request. example:
<?xml version="1.0"?>
<group id="3">
<point>
<value>70.152100</value>
</point>
<point>
<value>69.536700</value>
</point>
</group>
would be available in the params variable
params['group']['id'] # => '3'
if you're dead set on using nokogiri it sounds like you have malformed xml, try:
Nokogiri::XML.fragment(request.body.read)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With