Python类中使用ElementTree遇ParseError报错求助
解决ElementTree在类中解析XML报错的问题
嘿,我一眼就看出问题出在哪了!你遇到的这个xml.etree.ElementTree.ParseError: no element found: line 1, column 0报错,核心原因是文件指针被移动到文件末尾了。
你在Peppol类的__init__方法里,先调用了peppol_invoice.read()传给xmltodict.parse(),这一步会把文件对象的读取位置直接跳到文件结尾。等你再把同一个文件对象传给ET.parse()时,它根本读不到任何XML内容,自然会报“找不到元素”的错误。
下面给你两种可行的解决方案:
方案1:重置文件指针到开头
在调用ET.parse()之前,用seek(0)把文件指针移回文件起始位置,这样ElementTree就能正常读取内容了:
import xmltodict import xml.etree.ElementTree as ET class Peppol: def __init__(self, peppol_invoice): self.invoice = xmltodict.parse(peppol_invoice.read()) # 重置文件指针到文件开头 peppol_invoice.seek(0) self.root = ET.parse(peppol_invoice).getroot()
方案2:一次性读取文件内容到内存(更推荐)
这种方法只读取一次文件内容到变量中,再分别传给两个解析器,既减少了IO操作,也避免了文件指针操作的潜在问题:
import xmltodict import xml.etree.ElementTree as ET class Peppol: def __init__(self, peppol_invoice): # 一次性读取所有XML内容到内存 xml_content = peppol_invoice.read() self.invoice = xmltodict.parse(xml_content) # 用ElementTree的fromstring方法解析字符串内容 self.root = ET.fromstring(xml_content)
测试一下修改后的代码,你的open_invoice函数不需要改动,就能正常创建Peppol实例并解析XML发票啦~
内容的提问来源于stack exchange,提问作者r3d5un
相关产品推荐
相关产品推荐

