Python XML ElementTree 删除所有元素

Python XML ElementTree Removing All Elements

我正在编写一个脚本,如果子元素与 CSV 文件中的元素匹配,该脚本应该从 XML 文件中删除父元素。循环和 if 语句正常工作,但是当我添加删除时,它只是删除 table 中的所有内容,无论它是否匹配。我似乎无法弄清楚为什么要这样做。

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')

您应该只比较当前产品 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)