在Python中使用ElementTree发出名称空间规范

在Python中使用ElementTree发出名称空间规范,第1张

在Python中使用ElementTree发出名称空间规范

尽管文档另有说明,但我只能

<?xml>
通过同时指定xml_declaration和编码来获得声明。

您必须在已注册的名称空间中声明节点,以在文件中的节点上获取名称空间。这是您的代码的固定版本:

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")
输出(page.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>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5617012.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存