尽管docs不是这样说的,但我只能通过同时指定xml声明和编码来获得<?xml>声明。
必须在已注册的命名空间中声明节点,才能获取文件中节点的命名空间。以下是您的代码的固定版本: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")
输出(page.xml)<?xml version='1.0' encoding='utf-8'?>STUFF EVERYWHERE!
ElementTree也不太好看。以下是打印输出:<?xml version='1.0' encoding='utf-8'?>
STUFF EVERYWHERE!
您还可以声明默认命名空间,而无需注册: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')
输出(漂亮的打印间距是我的)<?xml version='1.0' encoding='utf-8'?>
STUFF EVERYWHERE!