Creating a doctype with lxml's etree
14,849
Solution 1
This worked for me:
print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")
Solution 2
The PI is actually added as a previous element from "doc". Thus, it's not a child of "doc". You must use "doc.getroottree()"
Here is an example:
>>> root = etree.Element("root")
>>> a = etree.SubElement(root, "a")
>>> b = etree.SubElement(root, "b")
>>> root.addprevious(etree.PI('xml-stylesheet', 'type="text/xsl" href="my.xsl"'))
>>> print etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<root>
<a/>
<b/>
</root>
with getroottree():
>>> print etree.tostring(root.getroottree(), pretty_print=True, xml_declaration=True, encoding='utf-8')
<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="my.xsl"?>
<root>
<a/>
<b/>
</root>
Author by
Marijn
Updated on June 05, 2022Comments
-
Marijn about 2 years
I want to add doctypes to my XML documents that I'm generating with LXML's etree.
However I cannot figure out how to add a doctype. Hardcoding and concating the string is not an option.
I was expecting something along the lines of how PI's are added in etree:
pi = etree.PI(...) doc.addprevious(pi)
But it's not working for me. How to add a to a xml document with lxml?