尽管文档另有说明,但我只能
<?xml>通过同时指定xml_declaration和编码来获得声明。
您必须在已注册的名称空间中声明节点,以在文件中的节点上获取名称空间。这是您的代码的固定版本:
输出(page.xml)from xml.etree import ElementTree as ETET.register_namespace('com',"http://www.company.com") #some name# build a tree structureroot = 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 XMLtree = ET.ElementTree(root)tree.write("page.xml",xml_declaration=True,encoding='utf-8',method="xml")
<?xml version='1.0' encoding='utf-8'?><com:STUFF xmlns:com="http://www.company.com"><com:MORE_STUFF>STUFF EVERYWHERe!</com:MORE_STUFF></com:STUFF>
ElementTree也不漂亮。这是打印精美的输出:
<?xml version='1.0' encoding='utf-8'?><com:STUFF xmlns:com="http://www.company.com"> <com:MORE_STUFF>STUFF EVERYWHERe!</com:MORE_STUFF></com:STUFF>
您还可以声明一个默认名称空间,而无需注册一个名称空间:
输出(漂亮的打印间隔是我的)from xml.etree import ElementTree as ET# build a tree structureroot = 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 XMLtree = 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 xmlns="http://www.company.com"> <MORE_STUFF>STUFF EVERYWHERe!</MORE_STUFF></STUFF>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)