2014-09-29 47 views
1

我正在使用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") 

的子元素的命名空间定义每时间命名空间附录ars,例如

<exp:bar xmlns:exp="http://www.example.com/exp/"> 
    <exp:fooHdr CREATEDATE="2013-03-22T10:28:27.137531"> 

这是格式良好的XML afaik,但我认为这不是必须的,它看起来很冗长。这种行为如何被压制?对于xml文件的根元素中的每个名称空间应该有一个定义。

在此先感谢!

UPDATE

最小示例

#!/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) 

UPDATE 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

我添加了一个片段。 – Steffen 2014-09-29 18:15:46

回答

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> 

这正是所需的输出。

+0

谢谢!有用!我推测'register_namespace'这样做(以某种方式)。 – Steffen 2014-09-30 10:11:38

相关问题