写作"漂亮的印刷"缩进xml到xml文件会导致错误的缩进级别

时间:2017-07-14 19:39:13

标签: python xml python-2.7 pretty-print

我开始使用Python将值写入XML文件以供数据库读取。首先,我使用了以下链接中的示例:

Pretty print XML trees in python

我使用了示例脚本:

from xml.etree import ElementTree as ET
'''
copy and paste from http://effbot.org/zone/element-lib.htm#prettyprint
it basically walks your tree and adds spaces and newlines so the tree is
printed in a nice way
'''
def indent(elem, level=0):
  i = "\n" + 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

'''
function to build an example tree containing cars and ships
vehicles is the root node
'''
def buildTree():
  vehicles = ET.Element("vehicles")

  cars = ET.SubElement(vehicles, "cars")
  cars.set("Type", "American")

  car1 = ET.SubElement(cars, "car")
  car1.text = "Ford Mustang"

  car2 = ET.SubElement(cars, "car")
  car2.text = "Dodge Viper"

  ships = ET.SubElement(vehicles, "ships")
  ships.set("Type", "sunken")

  ship1 = ET.SubElement(ships, "ship")
  ship1.text = "Titanic"

  indent(vehicles)

  tree = ET.ElementTree(vehicles)

  tree.write("vehicle_file.xml", xml_declaration=True, encoding='utf-8', method="xml")

'''
main function, so this program can be called by python program.py
'''
if __name__ == "__main__":
  buildTree()

打算在vehicle_file.xml中获取以下内容:

<?xml version='1.0' encoding='utf-8'?>
<vehicles>
  <cars Type="American">
    <car>Ford Mustang</car>
    <car>Dodge Viper</car>
  </cars>
  <ships Type="sunken">
    <ship>Titanic</ship>
  </ships>
</vehicles>

但我最终得到了:

<?xml version='1.0' encoding='utf-8'?>
<vehicles>
  <cars Type="American">
    <car>Ford Mustang</car>
    <car>Dodge Viper</car>
    </cars>
  <ships Type="sunken">
    <ship>Titanic</ship>
    </ships>
  </vehicles>

请注意,汽车,轮船和车辆的终端标签不会缩减,因为它会污染xml文件的其余部分。

作为检查,我在indent()函数中输入了一个调试语句,打印出级别和标记名称。我得到了正确的结果:

0 vehicles
1 cars
2 car
2 car
1 ships
2 ship

为什么indent()没有dedenting结束标记?我在indent()函数中遗漏了什么吗?   为什么结束标签没有缩进?我在缩进函数中错过了一个语句吗?

0 个答案:

没有答案