1

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

1
  • Have you looked at the lxml tutorial lxml.de/tutorial.html#namespaces - which part there do you ot understand so that we can try to explain Commented Oct 22, 2013 at 16:59

1 Answer 1

6

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>

>>>
Sign up to request clarification or add additional context in comments.

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.