我需要获取这个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>
据我所知,< Action >节点和它的属性"mustUnderstand“位于不同的名称空间下。我现在所取得的成就:
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>
正如我们所看到的,在"mustUnderstand“属性前面没有名称空间前缀。那么用lxml可以得到"s: mustUnderstand“吗?如果是,那是怎么做的?
发布于 2014-08-05 15:23:27
只需使用QName,就像处理元素名称一样:
action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"
发布于 2018-07-24 05:44:26
此外,如果您希望在单个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>
https://stackoverflow.com/questions/25132998
复制相似问题