Python 如何使用lxml向属性添加名称空间前缀(节点与其他名称空间一起)?

Python 如何使用lxml向属性添加名称空间前缀(节点与其他名称空间一起)?,python,xml,namespaces,lxml,Python,Xml,Namespaces,Lxml,我需要得到这个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:Envelop

我需要得到这个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>
结果:

<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>

http://schemas.xmlsoap.org/ws/2004/09/transfer/Create

如我们所见,“mustUnderstand”属性前面没有名称空间前缀。那么,是否有可能通过lxml获得“s:mustUnderstand”?如果是的话,怎么办

只需使用QName,就像使用元素名称一样:

action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"

此外,如果您想在单个子元素句子中创建所有属性,您可以利用其特性,即属性只是一个字典:

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>

这太棒了:)。非常感谢。
<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>