How can I use XML attributes when converting into

2019-08-02 06:55发布

问题:

I have an XML element with multiple child elements that use the same ID. The child elements are distinguishable by a "size" attribute. When I create a hash using from_xml it lumps all these child elements 1 field.

How do I parse these child elements into different fields based on the XML attribute?

XML:

<artist rank="48">
 <name>KISS</name>
  <image size="small">http://userserve-ak.last.fm/serve/34/3329738.jpg</image>
  <image size="medium">http://userserve-ak.last.fm/serve/64/3329738.jpg</image>
  <image size="large">http://userserve-ak.last.fm/serve/126/3329738.jpg</image>
  <image size="extralarge">http://userserve-ak.last.fm/serve/252/3329738.jpg</image>
  <image size="mega">http://userserve-ak.last.fm/serve/500/3329738/KISS+04.jpg</image>
</artist>

Ruby:

>>xml = "<artist rank='48'><name>KISS</name><image size='small'>http://userserve-ak.last.fm/serve/34/3329738.jpg</image><image size='medium'>http://userserve-ak.last.fm/serve/64/3329738.jpg</image><image size='large'>http://userserve-ak.last.fm/serve/126/3329738.jpg</image><image size='extralarge'>http://userserve-ak.last.fm/serve/252/3329738.jpg</image><image size='mega'>http://userserve-ak.last.fm/serve/500/3329738/KISS+04.jpg</image></artist>"
=> "<artist rank='48'><name>KISS</name><image size='small'>http://userserve-ak.last.fm/serve/34/3329738.jpg</image><image size='medium'>http://userserve-ak.last.fm/serve/64/3329738.jpg</image><image size='large'>http://userserve-ak.last.fm/serve/126/3329738.jpg</image><image size='extralarge'>http://userserve-ak.last.fm/serve/252/3329738.jpg</image><image size='mega'>http://userserve-ak.last.fm/serve/500/3329738/KISS+04.jpg</image></artist>"
>>h = Hash.from_xml xml
=> {"artist"=>{"name"=>"KISS", "rank"=>"48", "image"=>["http://userserve-ak.last.fm/serve/34/3329738.jpg", "http://userserve-ak.last.fm/serve/64/3329738.jpg", "http://userserve-ak.last.fm/serve/126/3329738.jpg", "http://userserve-ak.last.fm/serve/252/3329738.jpg", "http://userserve-ak.last.fm/serve/500/3329738/KISS+04.jpg"]}}

What I want:

=> {"artist"=>{"name"=>"KISS", "rank"=>"48", "image_small"=>"http://userserve-ak.last.fm/serve/34/3329738.jpg", "image_medium"="http://userserve-ak.last.fm/serve/64/3329738.jpg", "image_large"="http://userserve-ak.last.fm/serve/126/3329738.jpg", "image_extralarge"="http://userserve-ak.last.fm/serve/252/3329738.jpg", image_mega"="http://userserve-ak.last.fm/serve/500/3329738/KISS+04.jpg"}}

回答1:

Hash.to_xml currently won't do that. It's really just meant for the simplest cases.

But, there's an open ticket with some proposed patches. Still, I would recommend something like Nokogiri to parse your XML.