lxml: add namespace to input file

后端 未结 6 1546
不思量自难忘°
不思量自难忘° 2020-12-03 21:16

I am parsing an xml file generated by an external program. I would then like to add custom annotations to this file, using my own namespace. My input looks as below:

6条回答
  •  感情败类
    2020-12-03 21:53

    I wrote this function to add a namespace to the root element:

    def addns(tree, alias, uri):                
        root = tree.getroot()
        nsmap = root.nsmap
        nsmap[alias] = uri
        new_root = etree.Element(root.tag, attrib=root.attrib, nsmap=nsmap)
        new_root[:] = root[:]
        return new_root.getroottree()
    

    After applying this function, you get a new tree, but you can probably change the tree instance from the single objet from which you access the tree ... as you have a strong OO design!.

提交回复
热议问题