1

我要处理的 xml 是这样的(来自 dict api)。它给了我一个 xml 文件。所以我想从这个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>

我这样处理这个xml

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  

我想要一个简短的解决方案,有什么简短的解决方案吗?

4

1 回答 1

1

您可以使用 gem xml-simple

server_config = XmlSimple.xml_in(server_config_path,
                             {'keyAttr' => 'name', 'ForceArray' => false})

将返回带有 xml 结构的哈希。

于 2012-06-14T10:37:04.467 回答