Reputation: 324
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?
Upvotes: 6
Views: 10335
Reputation: 584
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>
Upvotes: 6
Reputation: 1840
Just use QName, like you do with element names:
action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"
Upvotes: 11