8

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 < Action > node and it's attribute "mustUnderstand" is under different namespaces. What I 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 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, no namespace prefix in front of "mustUnderstand" attribute. So is it possible to get "s: mustUnderstand" with lxml? if yes, then how?

2 Answers 2

12

Just use QName, like you do with element names:

action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"
Sign up to request clarification or add additional context in comments.

1 Comment

This is sweet:). Thank You!
6

Also if you want to create all attributes in single SubElement sentence, you can exploit its feature that attributes are just a dictionary:

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

The result is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.