Python: Update XML-file using ElementTree while conserving layout as much as possible

后端 未结 4 986
天命终不由人
天命终不由人 2021-01-04 03:36

I have a document which uses an XML namespace for which I want to increase /group/house/dogs by one: (the file is called houses.xml)



        
4条回答
  •  温柔的废话
    2021-01-04 04:27

    when Save xml add default_namespace argument is easy to avoid ns0, on my code

    key code: xmltree.write(xmlfiile,"utf-8",default_namespace=xmlnamespace)

    if os.path.isfile(xmlfiile):
                xmltree = ET.parse(xmlfiile)
                root = xmltree.getroot()
                xmlnamespace = root.tag.split('{')[1].split('}')[0]  //get namespace
    
                initwin=xmltree.find("./{"+ xmlnamespace +"}test")
                initwin.find("./{"+ xmlnamespace +"}content").text = "aaa"
                xmltree.write(xmlfiile,"utf-8",default_namespace=xmlnamespace)
    

提交回复
热议问题