在 Python 中测试空 xml 文件

Testing for an empty xml file in Python

我有 Python 脚本来将 XML 文件解析为对另一个平台更友好的格式。

经常有一个数据文件不包含任何数据 - 只有编码信息而没有其他标签,这导致 ElementTree 在找到它们时抛出 ParseError。

<?xml version="1.0" encoding="utf-8"?>

有没有办法在调用 ElementTree 之前测试空文件?

Ta.

当然有几种方式,使用:

try:
    pass # delete this and add your parse code
except:
    pass # write your exception when empty

或使用 if 语句:

if (some code to evalue if xml is not empty):
    # your code
elif (some code to check if .xml is empty):
    # your code

让我知道这是怎么回事!

当然你可以捕获 lxml 抛出的异常。如果你想避免解析,你可以检查文件是否只包含一个 < 符号:

with open("input.xml","rb") as f:
   contents = f.read()
   if contents.count(b"<")<=1:
      # empty or only header: skip
      pass
   else:
      x = etree.XML(contents)

当然,这种启发式方法不能防止其他解析错误。所以最好只用 try/except 块来保护解析。

但是如果你有很多损坏的 1 行 "header only" 文件,这种方法的优点是非常快。

你应该在这里请求原谅而不是许可

通过将代码包装在 try/except 块中来处理异常。

import xml.etree.ElementTree as ET
...
try:    
   tree = ET.parse(fooxml)
except ET.ParseError:
   # log error
   pass