Editing XML as a dictionary in python?

前端 未结 8 1188
深忆病人
深忆病人 2020-12-31 18:11

I\'m trying to generate customized xml files from a template xml file in python.

Conceptually, I want to read in the template xml, remove some elements, change some

8条回答
  •  [愿得一人]
    2020-12-31 18:21

    I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:

    import xml.etree.ElementTree as ET
    doc = ET.parse("template.xml")
    lvl1 = doc.findall("level1-name")[0]
    lvl1.remove(lvl1.find("leaf1")
    lvl1.remove(lvl1.find("leaf2")
    # or use del lvl1[idx]
    doc.write("config-new.xml")
    

    ElementTree was designed so that you don't have to convert your XML trees to lists and attributes first, since it uses exactly that internally.

    It also support as small subset of XPath.

提交回复
热议问题