python Elementtree 生成带缩进格式的xml文件

示例

之前拿ET写xml,直接对root节点调用write函数,会出现产生的xml字符串没有缩进,是干巴巴的一行,可读性比较差,就像下面这样:

<annotation><filename>VW_CH3ENTERPRIZEVsTaurus_BO2_1_4_7.jpg</filename><size><width>168.81600000000006</width><height>121.66920000000009</height></size><object><name>Car</name><bndbox><xmin>14.068</xmin><ymin>10.139</ymin><xmax>154.748</xmax><ymax>111.53</ymax><width>140.68000000000006</width><height>101.39100000000008</height></bndbox></object><object><name>RedArmor3</name><bndbox><xmin>71.108</xmin><ymin>68.439</ymin><xmax>116.728</xmax><ymax>93.787</ymax><width>45.61999999999989</width><height>25.347999999999956</height></bndbox></object><object><name>RedArmor3</name><bndbox><xmin>17.878</xmin><ymin>59.567</ymin><xmax>44.488</xmax><ymax>87.45</ymax><width>26.6099999999999</width><height>27.883000000000038</height></bndbox></object><object><name>RedArmor3</name><bndbox><xmin>39.418</xmin><ymin>44.359</ymin><xmax>72.368</xmax><ymax>74.776</ymax><width>32.950000000000045</width><height>30.41700000000003</height></bndbox></object></annotation>

解决办法

看到一个不错的方法:
https://www.cnblogs.com/muffled/p/3462157.html
原理 先对root进行修饰,调用一个自定义的修饰函数

def indent(elem, level=0):
    i = "
" + level*"	"
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "	"
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

之后的效果就会很棒:

<annotation>
	<filename>VW_CH3ENTERPRIZEVsTaurus_BO2_1_5_4.jpg</filename>
	<size>
		<width>207</width>
		<height>213</height>
	</size>
	<object>
		<name>Car</name>
		<bndbox>
			<xmin>17.237</xmin>
			<ymin>17.744</ymin>
			<xmax>189.602</xmax>
			<ymax>195.179</ymax>
			<width>172.4</width>
			<height>177.4</height>
		</bndbox>
	</object>
	<object>
		<name>RedArmor2</name>
		<bndbox>
			<xmin>140.173</xmin>
			<ymin>128.007</ymin>
			<xmax>173.125</xmax>
			<ymax>152.087</ymax>
			<width>33.0</width>
			<height>24.1</height>
		</bndbox>
	</object>
	<object>
		<name>RedArmor2</name>
		<bndbox>
			<xmin>51.457</xmin><annotation>
	<filename>VW_CH3ENTERPRIZEVsTaurus_BO2_1_5_4.jpg</filename>
	<size>
		<width>207</width>
		<height>213</height>
	</size>
	<object>
		<name>Car</name>
		<bndbox>
			<xmin>17.237</xmin>
			<ymin>17.744</ymin>
			<xmax>189.602</xmax>
			<ymax>195.179</ymax>
			<width>172.4</width>
			<height>177.4</height>
		</bndbox>
	</object>
	<object>
		<name>RedArmor2</name>
		<bndbox>
			<xmin>140.173</xmin>
			<ymin>128.007</ymin>
			<xmax>173.125</xmax>
			<ymax>152.087</ymax>
			<width>33.0</width>
			<height>24.1</height>
		</bndbox>
	</object>
	<object>
		<name>RedArmor2</name>
		<bndbox>
			<width>31.7</width>
			<height>27.9</height>
		</bndbox>
	</object>
</annotation>