オックスを見てください。XML を読み取り、XML の合理的な Ruby オブジェクトの複製を返します。
require 'ox'
hash = {'foo' => { 'bar' => 'hello world'}}
puts Ox.dump(hash)
pp Ox.parse_obj(Ox.dump(hash))
それを IRB にダンプすると、次のようになります。
require 'ox'
> hash = {'foo' => { 'bar' => 'hello world'}}
{
"foo" => {
"bar" => "hello world"
}
}
> puts Ox.dump(hash)
<h>
<s>foo</s>
<h>
<s>bar</s>
<s>hello world</s>
</h>
</h>
nil
> pp Ox.parse_obj(Ox.dump(hash))
{"foo"=>{"bar"=>"hello world"}}
{
"foo" => {
"bar" => "hello world"
}
}
とはいえ、あなたの XML サンプルは壊れており、OX では動作しません。Nokogiriで動作しますが、DOM を正しく解析できないことを示唆するエラーが報告されています。
私の質問は、なぜ XML をオブジェクトに変換したいのですか? Nokogiri のようなパーサーを使用して XML を処理する方がはるかに簡単です。XML の固定バージョンを使用する:
require 'nokogiri'
xml = '
<xml>
<page Title="System Slots" H1="Property" H2="Value" __type__="2">
<item Property="System Slot 1"/>
<item Property="Name" Value="PCI1"/>
<item Property="Type" Value="PCI"/>
<item Property="Data Bus Width" Value="32 bits"/>
<item Property="Current Usage" Value="Available"/>
<item Property="Characteristics">
<item Property="Vcc voltage supported" Value="3.3 V, 5.0 V"/>
<item Property="Shared" Value="No"/>
<item Property="PME Signal" Value="Yes"/>
<item Property="Support Hot Plug" Value="No"/>
<item Property="PCI slot supports SMBus signal" Value="Yes"/>
</item>
</page>
</xml>'
doc = Nokogiri::XML(xml)
page = doc.at('page')
page['Title'] # => "System Slots"
page.at('item[@Property="Current Usage"]')['Value'] # => "Available"
item_properties = page.at('item[@Property="Characteristics"]')
item_properties.at('item[@Property="PCI slot supports SMBus signal"]')['Value'] # => "Yes"
大きな XML ドキュメントをメモリに解析すると、配列とハッシュの迷路が返される可能性があり、必要な値にアクセスするには、これらをばらばらにする必要があります。Nokogiri を使用すると、学習と読み取りが容易な CSS および XPath アクセサーを使用できます。上記では CSS を使用しましたが、XPath を使用して同じことを簡単に行うことができました。