Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain XML file POST request to parse with Ruby on Rails

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!

like image 486
Brian Weinreich Avatar asked Oct 28 '11 20:10

Brian Weinreich


3 Answers

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
like image 120
Meekohi Avatar answered Sep 17 '22 17:09

Meekohi


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
like image 39
tokland Avatar answered Sep 19 '22 17:09

tokland


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)
like image 34
firien Avatar answered Sep 18 '22 17:09

firien