如何在Ruby on rails上将xml转换为json

时间:2016-12-20 13:41:38

标签: ruby-on-rails json ruby xml

<result>
    <sequence id="148"></sequence>
    <sequence id="211"></sequence>
    <sequence id="81">!Kyle OP Test</sequence>
    <sequence id="197">(SS) AnikSIB - 1 Hour Reminder</sequence>
    <sequence id="198">(SS) AnikSIB - 5 minutes Reminder</sequence>
<result>

如何将上述xml转换为json我希望序列ID如148,211,81,197和!Kyle OP Test,(SS)AnikSIB - 1小时提醒 我在尝试什么:Hash.from_xml(xmlresponce) 我的输出是:

{
  "result": {
    "sequence": [
      {
        "id": "148"
      },
      {
        "id": "211"
      },
      "!Kyle OP Test",
      "(SS) AnikSIB - 1 Hour Reminder",
      "(SS) AnikSIB - 5 minutes Reminder",

我想要!Kyle OP Test的序列ID,我不知道。

1 个答案:

答案 0 :(得分:0)

要以专业的方式处理XML文档,请使用nokogiri

require 'nokogiri'
doc = Nokogiri::XML(input) # XML document

doc.xpath("//sequence[text()='!Kyle OP Test']") # query for nodes with text
   .first                                       # first, since it’s unique
   .xpath("@id")                                # get attribute
   .first                                       # first, yeah
   .value                                       # value
#⇒ "81"