jhon.smith
jhon.smith

Reputation: 2043

adding namespace while creating a XML document using Python

I need to create a XML document using Python but i am unable to figure out how to add a

<?xml version="1.0" encoding="utf-8"?>

And how to add the namespace elements to the document tag

<Document xmlns="urn:iso:std:iso:2013:008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <page1 xmlns="urn:iso:std:iso:2013:008.001.02" </page1>
</Document>

Any examples please

Upvotes: 1

Views: 2713

Answers (1)

falsetru
falsetru

Reputation: 369274

To output xml declaration <?xml version="1.0" encoding="utf-8"?>, use lxml.etree.tostring with xml_declaration=True, encoding='utf-8' as argument.

To add namespace element, pass nsmap argument when creating element.

>>> import lxml.etree
>>>
>>> nsmap = {
...     None: "urn:iso:std:iso:2013:008.001.02",
...     'xsi': "http://www.w3.org/2001/XMLSchema-instance",
... }
>>> root = lxml.etree.Element('Document', nsmap=nsmap)
>>> lxml.etree.SubElement(root, 'page1')
<Element page1 at 0x2ad8af8>
>>> print lxml.etree.tostring(root, xml_declaration=True, encoding='utf-8', pretty_print=True)
<?xml version='1.0' encoding='utf-8'?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:2013:008.001.02">
  <page1/>
</Document>

>>>

Upvotes: 6

Related Questions