【发布时间】:2014-09-29 09:07:26
【问题描述】:
我正在使用 lxml 生成一个 xml 文件。
from lxml import etree as ET
我使用这一行注册了一个命名空间
ET.register_namespace("exp", "http://www.example.com/exp/")
如果我用
添加一个元素root_exp = ET.Element("{http://www.example.com/exp/}root_exp")
或带有
的子元素foo_hdr = ET.SubElement(root_exp, "{http://www.example.com/exp/}fooHdr")
每次出现命名空间时都会定义命名空间,例如
<exp:bar xmlns:exp="http://www.example.com/exp/">
<exp:fooHdr CREATEDATE="2013-03-22T10:28:27.137531">
这是格式良好的 XML afaik,但我认为这不是必需的,而且看起来非常冗长。如何抑制这种行为? xml 文件的根元素中的每个命名空间都应该有一个定义。
提前致谢!
更新
小例子
#!/usr/bin/env python2
from lxml import etree as ET
ET.register_namespace("exa", "http://www.example.com/test")
root = ET.Element("{http://www.example.com/test}root")
tree = ET.ElementTree(root)
tree.write("example.xml", encoding="UTF-8", pretty_print=True, xml_declaration=True)
更新 2
更新了sn-p
#!/usr/bin/env python2
from lxml import etree as ET
ET.register_namespace("exa", "http://www.example.com/test")
ET.register_namespace("axx", "http://www.example.com/foo")
root = ET.Element("{http://www.example.com/test}root")
sub_element = ET.SubElement(root, "{http://www.example.com/test}sub_element")
foo_element = ET.SubElement(sub_element, "{http://www.example.com/foo}foo")
bar_element = ET.SubElement(sub_element, "{http://www.example.com/foo}bar")
tree = ET.ElementTree(root)
tree.write("example.xml", encoding="UTF-8", pretty_print=True, xml_declaration=True)
预期:
<?xml version="1.0" encoding="UTF-8"?>
<exa:root xmlns:exa="http://www.example.com/test"/ xmlns:axx="http://www.example.com/foo">
<exa:sub_element>
<axx:foo />
<axx:bar />
</exa:sub_element>
</exa:root>
是:
<?xml version="1.0" encoding="UTF-8"?>
<exa:root xmlns:exa="http://www.example.com/test">
<exa:sub_element>
<axx:foo xmlns:axx="http://www.example.com/foo"/>
<axx:bar xmlns:axx="http://www.example.com/foo"/>
</exa:sub_element>
</exa:root>
【问题讨论】:
标签: python xml namespaces lxml