[英]new hash declaration in ruby returning syntax errors compared to command line
[英]Ruby Hash declaration with an inline block in the middle
這是一個XML文檔:
<Request>
<Field1>value1</Field1>
<Field2>value2</Field2>
<Section1>
<Field attribute1="attrval1">value11</Field>
<Field attribute1="attrval2">value12</Field>
<Field attribute1="attrval3">value13</Field>
<Field attribute1="attrval4">value14</Field>
</Section1>
<Section2>
<Fld1>value21</Fld1>
<Fld2>value22</Fld2>
<Fld3>value23</Fld3>
</Section2>
</Request>
通過以下Ruby代碼進行解析:
xml = Nokogiri::XML(request.raw_post)
req = xml.xpath('/Request')
hash = {
field1: req.xpath('Field1').text,
field2: req.xpath('Field2').text,
section1: req.xpath('Section1/Field').map {|fld|
{
attribute1: fld.attr('attribute1'),
value: fld.text
}
},
section2: req.xpath('Section2').some_method { |sec2|
{
fld1: sec2.xpath('Fld1').text,
fld2: sec2.xpath('Fld2').text,
fld3: sec2.xpath('Fld3').text
}
}
}
解析Section1是真正的工作代碼。
第2節中非重復值的解析是一個概念-我希望不必聲明
sec2 = req.xpath('Section2')
在哈希聲明之前。
我希望看到一些內聯塊。
有什么建議么?
無法回答,但是您可以嘗試以下方法:
ActiveSupport::XmlMini.parse(xml)
{"Request"=>
{"Field1"=>{"__content__"=>"value1"},
"Field2"=>{"__content__"=>"value2"},
"Section1"=>
{"Field"=>
[{"attribute1"=>"attrval1", "__content__"=>"value11"},
{"attribute1"=>"attrval2", "__content__"=>"value12"},
{"attribute1"=>"attrval3", "__content__"=>"value13"},
{"attribute1"=>"attrval4", "__content__"=>"value14"}]},
"Section2"=>
{"Fld1"=>{"__content__"=>"value21"},
"Fld2"=>{"__content__"=>"value22"},
"Fld3"=>{"__content__"=>"value23"}}}}
您也可以在這里使用map
:
req.xpath('Section2/*').map { |f| [f.name.downcase.to_sym, f.text] }.to_h
# => {:fld1=>"value21", :fld2=>"value22", :fld3=>"value23"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.