views:

58

answers:

3

Can anybody tell me how to parse this on rails.

<?xml version="1.0" encoding="utf-8"?>
<message>
  <param>
    <name>messageType</name>
    <value>SMS</value>
  </param>
  <param>
    <name>id</name>
    <value>xxxxxxxxxxxxxx</value>
  </param>
  <param>
    <name>source</name>
    <value>xxxxxxxxxxx</value>
  </param>
  <param>
    <name>target</name>
    <value>xxxxxxxxxxxxx</value>
  </param>
  <param>
    <name>msg</name>
    <value>xxxxxxxxxxxxx</value>
  </param>
  <param>
    <name>udh</name>
    <value></value>
  </param>
</message>

I have no control on this xml, but I hope I can make the parameter looks like this before saving to my database

message"=>{"msg"=>"sampler", "id"=>"1", "target"=>"23123", "source"=>"312321312"}

here is the parameter I received when it access my method

message"=>{"param"=>[{"name"=>"id", "value"=>"2373084120100804002252"}, {"name"=>"messageType", "value"=>"SMS"}, {"name"=>"target", "value"=>"23730841"}, {"name"=>"source", "value"=>"09156490046"}, {"name"=>"msg", "value"=>"Hello world via iPhone"}, {"name"=>"udh", "value"=>nil}]}
+1  A: 

There are a lot of Ruby XML parsing libraries. However, if your XML is small, you can use the ActiveSupport Hash extension 'from_xml':

Hash.from_xml(x)["message"]["param"].inject({}) do |result, elem| 
  result[elem["name"]] = elem["value"] 
  result 
end

=> {"msg"=>"xxxxxxxxxxxxx", "messageType"=>"SMS", "udh"=>nil, "id"=>"xxxxxxxxxxxxxx", "target"=>"xxxxxxxxxxxxx", "source"=>"xxxxxxxxxxx"}

Vlad Zloteanu
omg thanks a lot :)
Budgie
You're welcome! And welcome to the StackOverflow community! If the answer was correct and helped you, you should mark it as the accepted answer by clicking on the check box outline to the left of the answer. You can also vote it up, if you want. More info on stackoverflow.com/faq on section 'How do I ask questions here?'
Vlad Zloteanu
oh dude can you help me, what if the input is from @message = Message.new(params[:message]).. I don't know how to insert it on the X .. it gives me a NIL resultI'm using this but it doesnt work mobi = (params[:message]).to_xml
Budgie
how to make it work from this code :D @message = Message.new(params[:message]) respond_to do |format| if @message.save format.html { redirect_to(@message, :notice => 'Message was successfully created.') } format.xml { render :xml => @message, :status => :created, :location => @message } else format.html { render :action => "new" } format.xml { render :xml => @message.errors, :status => :unprocessable_entity } end end end
Budgie
A: 

Also, try checking out REXML for more complex problems.

Kevin Sylvestre
A: 

You should use Nokogiri for parsing xml. Its pretty fast.

Shripad K