2014-09-29 97 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

相關問題