2016-10-22 73 views
0

我需要生成XML,看起来像这样:与LXML生成XML - 属性的名称空间

<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
    <typeRef xmlns:ns2="xyz">text</typeRef> 
</definitions> 

我的代码如下:

class XMLNamespaces: 
    ex = 'http://www.example1.org' 
    xmlns = 'http://www.example2.org' 

root = Element('definitions', xmlns='http://www.example2.org', nsmap = {'ex':XMLNamespaces.ex}) 
type_ref = SubElement(root, 'typeRef') 
type_ref.attrib[QName(XMLNamespaces.xmlns, 'ns2')] = 'xyz' 
type_ref.text = 'text' 

tree = ElementTree(root) 
tree.write('filename.xml', pretty_print=True) 

结果是这样的:

<definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
    <typeRef xmlns:ns0="http://www.example2.org" ns0:ns2="xyz">text</typeRef> 
</definitions> 

所以这里是我的问题:

如何使属性看起来像xmlns:ns2 =“xyz”而不是xmlns:ns0 =“http://www.example2.org”ns0:ns2 =“xyz”

回答

1

只需运行与您的开始元素相同的进程,其中您定义了名称空间字典nsmap参数。注意类对象中添加的变量:

from lxml.etree import * 

class XMLNamespaces: 
    ex = 'http://www.example1.org' 
    xmlns = 'http://www.example2.org' 
    xyz = 'xyz' 

root = Element('definitions', xmlns='http://www.example2.org', nsmap={'ex':XMLNamespaces.ex}) 
type_ref = SubElement(root, 'typeRef', nsmap={'ns2':XMLNamespaces.xyz}) 
type_ref.text = 'text' 

tree = ElementTree(root) 
tree.write('filename.xml', pretty_print=True) 

# <definitions xmlns:ex="http://www.example1.org" xmlns="http://www.example2.org"> 
# <typeRef xmlns:ns2="xyz">text</typeRef> 
# </definitions>