inserting newlines in xml file generated via xml.etree.ElementTree in python

前端 未结 5 1618
北海茫月
北海茫月 2020-12-02 17:12

I have created a xml file using xml.etree.ElementTree in python. I then use

tree.write(filename, "UTF-8") 

to write out the documen

5条回答
  •  眼角桃花
    2020-12-02 17:15

    Without the use of external libraries, you can easily achieve a newline between each XML tag in the output by setting the tail attribute for each element to '\n'.

    You can also specify the number of tabs after the newline here. However, in the OP's use-case tabs may be easier to achieve with an external library, or see Erick M. Sprengel's answer.

    I ran into the same problem while trying to modify an xml document using xml.etree.ElementTree in python. In my case, I was parsing the xml file, clearing certain elements (using Element.clear()), and then writing the result back to a file.

    For each element that I had cleared, there was no new line after its tag in the output file.

    ElementTree's Element.clear() documentation states:

    This function removes all subelements, clears all attributes, and sets the text and tail attributes to None.

    This made me realize that the text and tail attributes of an element were how the output format was being determined. In my case, I was able to just set these attributes of the cleared element to the same values as before clearing it. This tail value ended up being '\n\t' for first-level children of the root xml element, with the number of tabs indicating the number of tabs displayed in the output.

提交回复
热议问题