2014-09-05 3 views
0

현재 한 부분을 제외하고는 올바르게 읽혀지는 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 필드를 뽑아 내 데이터베이스에 기록하는 방법?

답변

0

주셔서 감사합니다. 확실히 올바른 방향으로 나를 이끌었습니다. 내가 작동하도록하는 방법은 double 앞에 // 마침표를 추가하는 것이다.

plu_import.barcodes = xml.xpath('.//UPC_Code').map(&:content) 
1

.at은 항상 단일 요소를 반환합니다. 요소 배열을 가져 오려면 Item 요소 목록을 얻는 것처럼 xpath을 사용하십시오.

plu_import.barcodes = xml.xpath('//UPC_Code').map(&:content) 
+0

이것은 여전히 ​​첫 번째 UPC_Code 만 필드에 넣습니다. 두 개의 UPC_Code 필드를 거기에 넣지는 않습니다. –

+0

xpath 문에 오류가 있습니다. 모든 UPC_code 태그를 찾으려면 두 개의 '//'가 있어야합니다. – infused

+0

나는 그것을 알아 차리고 그것을 행운으로 내 코드에서 변경했다. 여전히 첫 번째 UPC_Code. –