我正在使用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
更新了代码段
#!/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>
答案 0 :(得分:1)
使用命名空间映射:
NSMAP = { 'exa': 'http://www.example.com/test',
'axx': 'http://www.example.com/foo' }
root = ET.Element('{http://www.example.com/test}root', nsmap=NSMAP)
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)
print(ET.tostring(tree,encoding='UTF-8',pretty_print=True,xml_declaration=True))
结果:
<?xml version='1.0' encoding='UTF-8'?>
<exa:root xmlns:axx="http://www.example.com/foo" xmlns:exa="http://www.examplom/test">
<exa:sub_element>
<axx:foo/>
<axx:bar/>
</exa:sub_element>
</exa:root>
这正是所需的输出。