python - how to write empty tree node as empty string to xml file

后端 未结 3 1273
花落未央
花落未央 2021-01-27 01:25

I want to remove elements of a certain tag value and then write out the .xml file WITHOUT any tags for those deleted elements; is my only option to create a new tre

3条回答
  •  梦谈多话
    2021-01-27 01:51

    The trick here is to find the parent (the country node), and delete the neighbor from there. In this example, I am using ElementTree because I am somewhat familiar with it:

    import xml.etree.ElementTree as ET
    
    if __name__ == '__main__':
        with open('debug.log') as f:
            doc = ET.parse(f)
    
            for country in doc.findall('.//country'):
                for neighbor in country.findall('neighbor'):
                    country.remove(neighbor)
    
            ET.dump(doc)  # Display
    

提交回复
热议问题