I’m using python’s lxml and I’m trying to read an xml document, modify and write it back but the original doctype and xml declaration disappears. I’m wondering if there’s an easy way of putting it back in whether through lxml or some other solution?
Share
tl;dr
The following will include the DOCTYPE and the XML declaration:
Note,
tostringdoes not preserve theDOCTYPEif you create anElement(e.g. usingfromstring), it only works when you process the XML usingparse.Update: as pointed out by J.F. Sebastian my assertion about
fromstringis not true.Here is some code to highlight the differences between
ElementandElementTreeserialization:and the output is: