Ruby-on-rails Rails XML 解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3403079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:59:53  来源:igfitidea点击:

Rails XML parsing

ruby-on-railsrubyxmlparsing

提问by Budgie

Can anybody tell me how to parse this on rails.

谁能告诉我如何在 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

我无法控制这个 xml,但我希望我可以在保存到我的数据库之前使参数看起来像这样

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}]}

回答by Vlad Zloteanu

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

有很多 Ruby XML 解析库。但是,如果您的 XML 很小,您可以使用 ActiveSupport Hash 扩展.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"}

回答by Shripad Krishna

You should use Nokogirifor parsing xml. Its pretty fast.

您应该使用Nokogiri来解析 xml。它的速度相当快。

回答by Kevin Sylvestre

Also, try checking out REXMLfor more complex problems.

此外,尝试检查REXML以了解更复杂的问题。