Emitting namespace specifications with ElementTree in Python

前端 未结 2 491
陌清茗
陌清茗 2020-12-04 18:09

I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:

from xml.etree import ElementTree          


        
2条回答
  •  不思量自难忘°
    2020-12-04 18:25

    I've never been able to get the tag out of the element tree libraries programatically so I'd suggest you try something like this.

    from xml.etree import ElementTree as ET
    root = ET.Element("STUFF")
    root.set('com','http://www.company.com')
    body = ET.SubElement(root, "MORE_STUFF")
    body.text = "STUFF EVERYWHERE!"
    
    f = open('page.xml', 'w')
    f.write('' + ET.tostring(root))
    f.close()
    

    Non std lib python ElementTree implementations may have different ways to specify namespaces, so if you decide to move to lxml, the way you declare those will be different.

提交回复
热议问题