我正在尝试创建一个更容易处理XML发票的类,但我在让ElementTree在类中工作时遇到了问题。
这是我想要做的事情的大致思路:
def open_invoice(input_file):
with open(input_file, 'r', encoding = 'utf8') as invoice_file:
return ET.parse(input_file).getroot()这可以很好地工作,并且我可以创建函数来处理数据而不会出现问题。但是当我试图在一个类中做同样的事情时,我得到了一个错误信息:
xml.etree.ElementTree.ParseError: no element found: line 1, column 0我认为这意味着解析器永远不会有任何东西需要解析,尽管我可能是错的。
类:
import xmltodict
import xml.etree.ElementTree as ET
class Peppol:
def __init__(self, peppol_invoice):
self.invoice = xmltodict.parse(
peppol_invoice.read()
)
self.root = ET.parse(peppol_invoice).getroot()创建类实例:
from pypeppol import Peppol
def open_invoice(input_file):
with open(input_file, 'r', encoding = 'utf8') as invoice_file:
return Peppol(invoice_file)
invoice = open_invoice('invoice.xml')非常感谢您的帮助。
发布于 2020-07-30 19:45:56
该错误表示invoice.xml为空,不包含XML或在XML数据之前包含XML +。
import xml.etree.ElementTree as ET
with open('empty.xml', 'w') as f:
f.write('')
# or
# f.write('No xml here!')
with open('empty.xml') as f:
ET.parse(f).getroot()
xml.etree.ElementTree.ParseError: no element found: line 1, column 0发布于 2020-07-30 20:24:13
这里的问题是,您试图读取文件peppol_invoice的内容两次,一次是在对xmltodict.parse的调用中,一次是在对ET.parse的调用中。
在对peppol_invoice.read()的调用完成后,peppol_invoice将指向文件的末尾。您会在问题标题中看到错误,因为当将peppol_invoice传递给ET.parse时,将没有任何内容可供从文件中读取。
如果您希望再次读取文件的内容,请调用peppol_invoice.seek(0)将指针重置回文件的开头:
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) # add this line
self.root = ET.parse(peppol_invoice).getroot()https://stackoverflow.com/questions/63172379
复制相似问题