我正在编写一个脚本,该脚本应该在子元素与CSV文件中的元素匹配的情况下从XML文件中删除父元素。循环和if语句运行正常,但是,当我添加remove时,它只会删除表中的所有内容,无论是否匹配。我似乎无法弄清楚为什么要这样做。
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')
在您的代码中,您从xml中获取所有产品ID,并将它们与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')
您应该只比较csv文件每个ID的当前产品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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句