用Nokogiri读取XML文件
问题描述:
我目前有一个XML文件,除了一部分以外,它正确读取。这是一个项目列表,有时一个项目有多个条形码。在我的代码中,它只提取第一个。我如何迭代多个条形码。请看下面的代码:用Nokogiri读取XML文件
def self.pos_import(xml)
Plu.transaction do
Plu.delete_all
xml.xpath('//Item').each do |xml|
plu_import = Plu.new
plu_import.update_pointer = xml.at('Update_Type').content
plu_import.plu = xml.at('item_no').content
plu_import.dept = xml.at('department').content
plu_import.item_description = xml.at('item_description').content
plu_import.price = xml.at('item_price').content
plu_import.barcodes = xml.at('UPC_Code').content
plu_import.sync_date = Time.now
plu_import.save!
end
end
我的测试XML文件是这样的:
<?xml version="1.0" encoding="UTF-16" standalone="no"?>
<items>
<Item>
<Update_Type>2</Update_Type>
<item_no>0000005110</item_no>
<department>2</department>
<item_description>DISC-ALCOHOL PAD STERIL 200CT</item_description>
<item_price>7.99</item_price>
<taxable>No</taxable>
<Barcode>
<UPC_Code>0000005110</UPC_Code>
<UPC_Code>1234567890</UPC_Code>
</Barcode>
</Item>
</Items>
任何想法如何拉两个UPC_Code场出来,他们写信给我的数据库?
答
感谢您的所有重要提示。这无疑使我朝着正确的方向前进。我得到它的工作方式只是在双击之前添加一段时间//。
plu_import.barcodes = xml.xpath('.//UPC_Code').map(&:content)
答
.at
将始终返回单个元素。要获得一组元素,使用xpath
就像获得Item元素的列表一样。
plu_import.barcodes = xml.xpath('//UPC_Code').map(&:content)
这仍然只是把第一个UPC_Code放到字段中。它不会将两个UPC_Code字段放在那里。 – 2014-09-05 16:43:52
xpath语句中有错误。它应该有两个'''来查找所有的UPC_code标签。 – infused 2014-09-05 18:00:25
我注意到了,并在我的代码中改变了它,但没有运气。仍然只是第一个UPC_Code。 plu_import.barcodes = xml.xpath('// UPC_Code')。map(&:content) – 2014-09-05 18:31:55