Python XML Remove Some Elements and Their Children but Keep Specific Elements and Their Children

后端 未结 1 1458
旧时难觅i
旧时难觅i 2020-12-21 17:50

I have a very large .xml file and I am trying to make a new .xml file that just has a small part of this larger file\'s contents. I want to specify an attribute (in my case

相关标签:
1条回答
  • 2020-12-21 18:26

    It's not very clear exactly what you're after, but this code produces the output you say you'd like:

    from lxml import etree as ET
    
    def filter_by_itemid(doc, idlist):
        rowset = doc.xpath("/api/result/rowset[@name='assets']")[0]
        for elem in rowset.getchildren():
            if int(elem.get("itemID")) not in idlist:
                rowset.remove(elem)
        return doc
    
    doc = ET.parse("test.xml")
    filter_by_itemid(doc, [1004072840841])
    
    print(ET.tostring(doc))
    
    0 讨论(0)
提交回复
热议问题