Reputation: 13
The xml I want to deal with is like this (from an dict api). It gives me back a xml file. So I want to get a solution from this xml.
<?xml version="1.0" encoding="UTF-8"?>
<dict num="219" id="219" name="219">
<key>renown</key>
<ps>riˈnaun</ps>
<pron>http://res.iciba.com/resource/amp3/0/0/d5/7a/d57a74f04be82105a2e51d1bed71a667.mp3</pron>
<ps>rɪˈnaʊn</ps>
<pron>http://res.iciba.com/resource/amp3/1/0/d5/7a/d57a74f04be82105a2e51d1bed71a667.mp3</pron>
<pos>n.</pos>
<acceptation>名望,声誉;</acceptation>
<sent>
<orig>
His renown has spread throughout the country.
</orig>
<trans>
他的名声已传遍全国。
</trans>
</sent>
<sent>
<orig>
It's just these heart-thrilling chapters that brought his work world renown.
</orig>
<trans>
正因这些扣人心弦的篇章才使得他的作品举世闻名。
</trans>
</sent>
</dict>
I deal with this xml like this way
require 'rexml/document'
include REXML
def parse
doc = Document.new(@result)
doc.elements.each("dict/key") { |e| puts e.text }
doc.elements.each("dict/ps") { |e| puts "[" + e.text + "]" }
pos_array = Array.new()
doc.elements.each("dict/pos") { |e| pos_array.push(e.text) }
acc_array = Array.new()
doc.elements.each("dict/acceptation") { |e| acc_array.push(e.text) }
pos_array.each_index { |i| puts pos_array[i] + " " + acc_array[i] }
pos_array.clear
doc.elements.each("dict/sent/orig") { |e| pos_array.push(e.text) }
acc_array.clear
doc.elements.each("dict/sent/trans") { |e| acc_array.push(e.text) }
pos_array.each_index { |i| puts "例句" + (i+1).to_s + ":" + pos_array[i] + " " + acc_array[i] }
end
I want a short solution,any short sloution?
Upvotes: 1
Views: 91
Reputation: 6922
You can use gem xml-simple
server_config = XmlSimple.xml_in(server_config_path,
{'keyAttr' => 'name', 'ForceArray' => false})
Will return hash with xml structure.
Upvotes: 1