Skip to content

Instantly share code, notes, and snippets.

@larsks
Created September 1, 2016 04:26
Show Gist options
  • Save larsks/de0d32d3796609cd856da7b95e7e4808 to your computer and use it in GitHub Desktop.
Save larsks/de0d32d3796609cd856da7b95e7e4808 to your computer and use it in GitHub Desktop.
Writing XML doctype and processing instructions with lxml

If you use lxml.etree, you can write an XML processing instruction (<? ... ?>) like this:

>>> from lxml import etree
>>> doc = etree.ElementTree(etree.fromstring('<data/>'))
>>> doc.getroot().addprevious(etree.ProcessingInstruction('xml', 'version=1.0'))
>>> print etree.tostring(doc)
<?xml version=1.0?><data/>

You can set doctype attribute when writing your XML by setting the doctype parameter of, e.g., etree.tostring:

>>> print etree.tostring(doc, doctype='<!doctype email-template PUBLIC "-//yourcompany, Inc.//DTD email-template//EN" "email-template.dtd">')
<!doctype email-template PUBLIC "-//yourcompany, Inc.//DTD email-template//EN" "email-template.dtd">
<?xml version=1.0?><data/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment