【发布时间】:2014-02-26 10:52:38
【问题描述】:
在我的 Python 代码中,我目前正在使用 xml.etree 库来创建一棵树,然后将其转储到 XML 字符串中。不幸的是,我不能使用 Python 标准库中的模块以外的模块来执行此操作。
这是我的代码:
import xml.etree.ElementTree as ET
def dump_to_XML():
root_node = ET.Element("root")
c1_node = ET.SubElement(root_node, "child1")
c1_node.text = "foo"
c2_node = ET.SubElement(root_node, "child2")
gc1_node = ET.SubElement(c2_node, "grandchild1")
gc1_node.text = "bar"
return ET.tostring(root_node, encoding='utf8', method='xml')
给出字符串:
<?xml version='1.0' encoding='utf8'?>
<root>
<child1>foo</child1>
<child2>
<grandchild1>bar</grandchild1>
</child2>
</root>
现在,我有两个架构文件位于 - 比如 - http://myhost.com/p.xsd 和 http://myhost.com/q.xsd,我希望将输出字符串转换为:
<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:p="http://myhost.com/p.xsd" xmlns:q="http://myhost.com/q.xsd">
<p:child1>foo</p:child1>
<p:child2>
<q:grandchild1>bar</q:grandchild1>
</p:child2>
</root>
我如何利用etree 库来实现这一目标?
提前致谢
【问题讨论】:
标签: python schema xml-namespaces elementtree