我不太确定XML的语法是什么,这就是为什么我将把两种类型的XML,请指出好的一个。
我有一个具有多个值的节点的XML:
案例1:
<items>
<item>
<image_urls>http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg
</image_urls>
</item>
</items>
案例2:
<items>
<item>
<image_urls>
http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg
</image_urls>
<image_urls>http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg
</image_urls>
</item>
</items>
我面临的困难是与Nokogiri一起得到多值节点。我试着:
item.at("image_urls").to_s.split(" ").inject([]) { |result, element|
result << element
}
但是这只适用于XML的第一个变体。如果正确的语法是第二种形式,我相信它是,我怎么能接受这两个值,因为我下面的实现只接受第一种?
xml = Nokogiri::XML(File.open(self.file.current_path))
xml.xpath("//item").each do |item|
attachments_array = item.at("image_urls").inject([]) { |result, element|
result << element
}
您需要使用css
方法,它返回所有匹配项,而at
只返回第一个匹配项:
text = <<EOD
<items>
<item>
<image_urls>http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg
</image_urls>
</item>
<item>
<image_urls>
http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg</image_urls>
<image_urls>http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg
</image_urls>
</item>
</items>
EOD
xml = Nokogiri::XML(text)
xml.css('item').each do |item|
attachments = item.css('image_urls').map do |url|
url.text.strip!.split(' ')
end.flatten
p attachments
end
# ["http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg", "http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg"]
# ["http://static.elefant.ro/images/26/95226/husa-belkin-grip-pentru-kindle-3-ebook-reader-albastru_1_categorie.jpg", "http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg"]