from lxml import etree
from io import StringIO
tree = etree.parse(StringIO(
    """<?xml version="1.0" encoding="iso-8859-1"?>
 <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "eggs"> ]>
  <root>
   <a>&tasty;</a>
 </root>
"""
    ))
docinfo = tree.docinfo
print(etree.tostring(tree, xml_declaration=True, encoding=docinfo.encoding))
Preserving original doctype and declaration of an lxml.etree parsed xml