且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-24 23:21:04

尽管文档否则,我只能得到<?xml> 声明通过同时指定xml_declaration和编码。

Although the docs say otherwise, I only was able to get an <?xml> 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")



输出(page.xml)



Output (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也不漂亮。这是输出精美的输出:

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

<?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>






您也可以声明默认名称空间,并且不要t需要注册一个:


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)

<?xml version='1.0' encoding='utf-8'?>
<STUFF xmlns="http://www.company.com">
    <MORE_STUFF>STUFF EVERYWHERE!</MORE_STUFF>
</STUFF>