How to preserve namespaces when parsing xml via ElementTree in Python

后端 未结 1 2056
执笔经年
执笔经年 2021-01-06 01:29

Assume that I\'ve the following XML which I want to modify using Python\'s ElementTree:


  

        
1条回答
  •  礼貌的吻别
    2021-01-06 01:55

    Here is the way to preserve the namespaces' prefix and URI:

    def register_all_namespaces(filename):
        namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])
        for ns in namespaces:
            ET.register_namespace(ns, namespaces[ns])
    

    This method should be called before calling the [ET].write() method.

    0 讨论(0)
提交回复
热议问题