Creating a doctype with lxml's etree

Marijn picture Marijn · Jun 14, 2009 · Viewed 13.8k times · Source

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?

Answer

hgb picture hgb · Jul 2, 2012

This worked for me:

print etree.tostring(tree, pretty_print=True, xml_declaration=True, encoding="UTF-8", doctype="<!DOCTYPE TEST_FILE>")