我需要得到这个xml:
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.or/2003/05/soap-envelope">
<s:Header>
<a:Action s:mustUnderstand="1">Action</a:Action>
</s:Header>
</s:Envelope>
据我了解&lt;行动&gt;节点和它的属性&#34; mustUnderstand&#34;在不同的名称空间下。 我现在取得的成就:
from lxml.etree import Element, SubElement, QName, tostring
class XMLNamespaces:
s = 'http://www.w3.org/2003/05/soap-envelope'
a = 'http://www.w3.org/2005/08/addressing'
root = Element(QName(XMLNamespaces.s, 'Envelope'), nsmap={'s':XMLNamespaces.s, 'a':XMLNamespaces.a})
header = SubElement(root, QName(XMLNamespaces.s, 'Header'))
action = SubElement(header, QName(XMLNamespaces.a, 'Action'))
action.attrib['mustUnderstand'] = "1"
action.text = 'Action'
print tostring(root, pretty_print=True)
结果:
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<a:Action mustUnderstand="1">http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action>
</s:Header>
</s:Envelope>
正如我们所看到的,&#34; mustUnderstand&#34;前面没有名称空间前缀。属性。那么有可能得到&#34; s: mustUnderstand&#34;用lxml?如果有,那怎么样?
答案 0 :(得分:5)
只需使用QName,就像使用元素名称一样:
action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"
答案 1 :(得分:1)
如果您想在单个SubElement句子中创建所有属性,则可以利用其功能,即属性只是字典:
from lxml.etree import Element, SubElement, QName, tounicode
class XMLNamespaces:
s = 'http://www.w3.org/2003/05/soap-envelope'
a = 'http://www.w3.org/2005/08/addressing'
root = Element(QName(XMLNamespaces.s, 'Envelope'), nsmap={'s':XMLNamespaces.s, 'a':XMLNamespaces.a})
header = SubElement(root, QName(XMLNamespaces.s, 'Header'))
action = SubElement(header, QName(XMLNamespaces.a, 'Action'), attrib={
'notUnderstand':'1',
QName(XMLNamespaces.s, 'mustUnderstand'):'1'
})
print (tounicode(root, pretty_print=True))
结果是:
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<a:Action notUnderstand="1" s:mustUnderstand="1"/>
</s:Header>
</s:Envelope>