2016-12-22 5 views
0

자식 요소가 CSV 파일의 요소와 일치하는 경우 XML 파일에서 부모 요소를 제거하기로되어있는 스크립트를 작성하고 있습니다. 루프 및 if 문이 올바르게 작동하지만 remove를 추가하면 일치하는지 여부에 관계없이 테이블의 모든 내용이 삭제됩니다. 왜 이런 일을하는지 알 수가 없어.Python XML ElementTree 모든 요소 제거

cs = open('skus.csv', 'rb') 
reader = csv.reader(cs) 


tree = et.parse('christmas-dog-price.xml') 
root = tree.getroot() 
xmlns = {'pricebook': '{http://www.demandware.com/xml/impex/pricebook/2006-10-31}'} 
price_table = root.find('.//{pricebook}price-table'.format(**xmlns)) 
product_id = [price_table.get('product-id') for price_table in root] 
for sku in reader: 
    for product in product_id: 
     for price_table in root: 
      if sku[0] != product: 
       continue 
      if sku[0] == product: 
       root.remove(price_table) 
      tree.write('please-work.xml') 
+0

이'tree.write ('please-work.xml')이 (가) 루프 외부에 있지 않아야합니까? –

+0

'product'와'root'와'tree'에 대한 xml 구조체와 변수 초기화를 공유하십시오. –

+0

@VikashSingh 예제 xml 구조체 (헤더 없음) : <가격 테이블 product-id = "tr-33373"> <수량 수량 = "1"> 11.99

답변

1

코드에서 모든 제품 ID를 xml 형식으로 만들고이를 csv 파일의 각 ID와 비교합니다. 일치하는 항목이 있으면 루트에서 모든 요소를 ​​제거합니다.

귀하의 코드는 다음에 해당합니다 :이 동일합니다

for sku in reader: 
    for product in product_id: 
     if sku[0] == product: 
      for price_table in root: 
       root.remove(price_table) 
tree.write('please-work.xml') 

:

if any(sku[0] in product_id for sku in reader): 
    for price_table in root: 
     root.remove(price_table) 
tree.write('please-work.xml') 

당신은 현재 제품 ID를 비교해야하는 CSV 파일의 각 ID :

with open('skus.csv', 'rb') as cs: 
    reader = csv.reader(cs) 
    product_ids = [sku[0] for sku in reader] 

tree = et.parse('christmas-dog-price.xml') 
root = tree.getroot() 
xmlns = {'pricebook': '{http://www.demandware.com/xml/impex/pricebook/2006-10-31}'} 
price_table = root.find('.//{pricebook}price-table'.format(**xmlns)) 
to_be_removed = [element for element in price_table if price_table.get('product-id') in product_ids] 
for element in to_be_removed: 
    root.remove(element) 
+0

이것은 완전히 의미가 있습니다. 고맙습니다 –