Emitting namespace specifications with ElementTree in Python

前端 未结 2 493
陌清茗
陌清茗 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:30

    Although the docs say otherwise, I only was able to get an declaration by specifying both the xml_declaration and the encoding.

    You have to declare nodes in the namespace you've registered to get the namespace on the nodes in the file. Here's a fixed version of your code:

    from xml.etree import ElementTree as ET
    ET.register_namespace('com',"http://www.company.com") #some name
    
    # build a tree structure
    root = ET.Element("{http://www.company.com}STUFF")
    body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF")
    body.text = "STUFF EVERYWHERE!"
    
    # wrap it in an ElementTree instance, and save as XML
    tree = ET.ElementTree(root)
    
    tree.write("page.xml",
               xml_declaration=True,encoding='utf-8',
               method="xml")
    

    Output (page.xml)

    STUFF EVERYWHERE!
    

    ElementTree doesn't pretty-print either. Here's pretty-printed output:

    
    
        STUFF EVERYWHERE!
    
    

    You can also declare a default namespace and don't need to register one:

    from xml.etree import ElementTree as ET
    
    # build a tree structure
    root = ET.Element("{http://www.company.com}STUFF")
    body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF")
    body.text = "STUFF EVERYWHERE!"
    
    # wrap it in an ElementTree instance, and save as XML
    tree = ET.ElementTree(root)
    
    tree.write("page.xml",
               xml_declaration=True,encoding='utf-8',
               method="xml",default_namespace='http://www.company.com')
    

    Output (pretty-print spacing is mine)

    
    
        STUFF EVERYWHERE!
    
    

提交回复
热议问题