How do I add a namespace prefix to an attribute with lxml (node โ€‹โ€‹with a different namespace)?

I need to get this 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>

      

As I understand it, Action> node and the "mustUnderstand" attribute is under different namespaces. What I have achieved now:

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)

      

And the result:

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

      

As we can see, the namespace prefix is โ€‹โ€‹before the mustUnderstand attribute. So is it possible to get " s: mustUnderstand" using lxml? if so, how?

+3


source to share


1 answer


Just use QName as you would for element names:



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

      

+4


source







All Articles