35

我正在尝试使用包含 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("STUFF")
body = ET.SubElement(root, "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,
           method="xml" )

但是,既不会出现<?xml标记,也不会出现任何命名空间/前缀信息。我在这里有点困惑。

4

2 回答 2

43

尽管文档另有说明,但我只能<?xml>通过同时指定 xml_declaration 和编码来获得声明。

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

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'?><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 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 xmlns="http://www.company.com">
    <MORE_STUFF>STUFF EVERYWHERE!</MORE_STUFF>
</STUFF>
于 2011-02-15T03:00:26.110 回答
8

我从来没有能够以<?xml编程方式从元素树库中获取标签,所以我建议你尝试这样的事情。

from xml.etree import ElementTree as ET
root = ET.Element("STUFF")
root.set('com','http://www.company.com')
body = ET.SubElement(root, "MORE_STUFF")
body.text = "STUFF EVERYWHERE!"

f = open('page.xml', 'w')
f.write('<?xml version="1.0" encoding="UTF-8"?>' + ET.tostring(root))
f.close()

非标准库 python ElementTree 实现可能有不同的方式来指定命名空间,所以如果你决定迁移到 lxml,你声明这些的方式会有所不同。

于 2011-02-14T22:39:39.667 回答