简体   繁体   中英

How to add namespace prefix at root XML using Python LXML?

I would like to have the following NS prefix <qsp: and </qsp:

<qsp:QSPart xmlns:qsp="urn:qvalent:quicksuper:gateway">
  <qsp:MemberRegistrationRequest/>
</qsp:QSPart>

How do I do that in LMXL python?

from lxml import etree

nsmap = {'qsp': 'urn:qvalent:quicksuper:gateway'}
nsprefix = nsmap['qsp']

QSPart = etree.Element('QSPart', nsmap=nsmap)
MemberRegistrationRequest = etree.SubElement(QSPart, etree.QName(nsprefix, 'MemberRegistrationRequest'))

print(etree.tostring(QSPart, pretty_print=True, encoding=str))

Result:

<QSPart xmlns:qsp="urn:qvalent:quicksuper:gateway">
  <qsp:MemberRegistrationRequest/>
</QSPart>

According to the documentation , you need to fully qualify the element name in your call to etree.Element :

from lxml import etree

nsmap = {'qsp': 'urn:qvalent:quicksuper:gateway'}
nsprefix = nsmap['qsp']

QSPart = etree.Element(f'{{{nsmap["qsp"]}}}QSPart')
MemberRegistrationRequest = etree.SubElement(QSPart, etree.QName(nsprefix, 'MemberRegistrationRequest'))

print(etree.tostring(QSPart, pretty_print=True, encoding=str))

This outputs:

<ns0:QSPart xmlns:ns0="urn:qvalent:quicksuper:gateway">
  <ns0:MemberRegistrationRequest/>
</ns0:QSPart>

Since you know your expected output, I wouldn't bother with all that (though I understand many people frown on this approach...) - just use from and to string:

frag_text = """<qsp:QSPart xmlns:qsp="urn:qvalent:quicksuper:gateway">
  <qsp:MemberRegistrationRequest/>
</qsp:QSPart>"""
fragment = etree.fromstring(frag_text)
print(etree.tostring(fragment).decode())

Output should be your expected output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM