lxml: add namespace to input file

后端 未结 6 1507
不思量自难忘°
不思量自难忘° 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:47

    If you temporarily add a namespaced attribute to the root node, that does the trick.

    ns = '{http://this.is.some/custom_namespace}'
    
    # add 'kjw:foobar' attribute to root node
    root.set(ns+'foobar', 'foobar')
    
    # add kjw namespace elements (or attributes) elsewhere
    ... get child element species ...
    species.append(etree.Element(ns + 'test'))
    
    # remove temporary namespaced attribute from root node
    del root.attrib[ns+'foobar']
    

提交回复
热议问题