Obtain XML file POST request to parse with Ruby on Rails
Asked Answered
S

3

10

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!

Semantics answered 28/10, 2011 at 20:47 Comment(0)
A
13

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
Addams answered 28/10, 2011 at 21:7 Comment(0)
G
3

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)
Galven answered 28/10, 2011 at 21:40 Comment(2)
Thanks! Everything is all set now.Semantics
This feature was removed from Rails core starting with Rails 4. We need to use a separate gem now github.com/rails/actionpack-xml_parserAffright
S
2

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
Scintillator answered 5/4, 2017 at 20:21 Comment(1)
I've improved upon this slightly by adding an .with_indifferent_access onto the end of the Hash line, to allow indifferent access.Footloose

© 2022 - 2024 — McMap. All rights reserved.