0

I am using python to deal with xml file, I need to insert one line to the xml file, and the code is like this:

xobj = ET.parse('/src/xxx.xml')
xroot = xobj.getroot()
filename = ET.Element("filename")
filename.text = xmlname
xroot.insert(0, filename)

tree = ET.ElementTree(xroot)
tree.write('/dst/xxx.xml')

It did insert one line of contents to the original xml file, but it was not a line. My xml file becomes:

 <filename>004228.xml</filename><object>
....
</object>

There should be a \n between </filename> and <object>, but this method does not have that line spliter, how could I make the format look nice ?

coin cheung
  • 949
  • 2
  • 10
  • 25
  • 1
    Does this answer your question? [inserting newlines in xml file generated via xml.etree.ElementTree in python](https://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python) – dspencer Mar 24 '20 at 03:06
  • I am afraid not, switching to lxml and add `pretty_print=True` does not work for me.. – coin cheung Mar 24 '20 at 03:26
  • 1
    @coincheung Did you see the other question which is linked in the comments of the accepted answer? It might be useful. (I would share the link directly, but I’m using the SE mobile app and it seems to be buggy) – AMC Mar 24 '20 at 04:04
  • @AMC yes, the accepted answer in the other comment shows that I should use `tree.write(filename, pretty_print=True)`, which seems not work for me. – coin cheung Mar 24 '20 at 05:40
  • @coincheung Sorry if my comment wasn’t clear, I was referring to the following answer: https://stackoverflow.com/a/7904066/11301900 – AMC Mar 24 '20 at 12:40

0 Answers0