首页 > 解决方案 > python xml读取文件

问题描述

我希望有人能帮忙。我无法读取 XML 文件并尝试了许多建议的解决方案。首先是文件:

<Program>
 <20180531 />
 <20180601 />
 <20180602 />
 <20180603 />
 <20180604 />
 <20180605 />
 <20180606 />
 <20180607 />
 <20180608 />
 <20180609 />
 <20180610 />
 <20180611 />
 <20180612 />
 <20180613 />
 <20180614 />
 <20180615 />
 <20180616 />
 <20180617 />
 <20180618 />
 <20180619 />
 <20180620 />
 <20180621 />
 <20180622 />
 <20180623 />
 <20180624 />
 <20180625 />
 <20180626 />
 <20180627 />
 <20180628 />
 <20180629 />
 <20180630 />
 <20180701 />
 <20180702 />
 <20180703 />
 <20180704 />
</Program>

真的只是一些约会。该文件是通过调用生成的

   import xml.etree.ElementTree as etree
   top = etree.Element('Program')
   for day in alldays: # alldays is a list of dates using datetime
       dan = etree.SubElement(top, day.strftime('%Y%m%d'))
       tree = etree.ElementTree(top)
       tree.write(directory + omnifile)

但我无法通过调用读取此文件:

 tree = etree.parse(somefile)

我收到此错误:xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 10

我没有看到问题,也无法理解为什么 ElementTree 生成的文件无法被 ElemenTree 读取。我在 Fedora 中使用 Python 3.6.5。

标签: xmlpython-3.xelementtree

解决方案


“XML”文件格式不正确。元素名称不允许以数字开头。请注意,数字不包括NameStartChar在 XML 语法的生成中:https ://www.w3.org/TR/xml/#NT-NameStartChar 。

ElementTree 在创建 XML 输出时有点松懈。另一方面,lxml不会让你这样做。如果您尝试,将会出现“Invalid tag name”错误。


推荐阅读