How can I include the declaration of an xml document when writing it to a new file? [duplicate]




This question already has an answer here:




I have an xml file named test.xml which has declaration and inner css like this:



<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?xml-stylesheet href="#style" type="text/css"?>
<!DOCTYPE document
[
<!ELEMENT document (entry)>
]>
<document>
<entry>this is a test document.</entry>
</document>


I want to modify this file and write it to a new file using Python 3.2. But I don't know how to include the part preceding the root node--declaration and css parts. Here is my code:



# -*- coding: utf-8 -*-
import lxml.etree as ET
with open('test_output.xml', 'w') as fout:
with open('test.xml', 'r') as fin:
xml = ET.parse(fin)
root = xml.getroot()
fout.write(ET.tostring(root, encoding="unicode"))


The output is:



<document>
<entry>this is a test document.</entry>
</document>


The first six lines are missing.


No comments:

Post a Comment