首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >'xml.etree.ElementTree.ParseError:在创建python类时未找到元素‘

'xml.etree.ElementTree.ParseError:在创建python类时未找到元素‘
EN

Stack Overflow用户
提问于 2020-07-30 19:37:36
回答 2查看 771关注 0票数 0

我正在尝试创建一个更容易处理XML发票的类,但我在让ElementTree在类中工作时遇到了问题。

这是我想要做的事情的大致思路:

代码语言:javascript
复制
def open_invoice(input_file):
    with open(input_file, 'r', encoding = 'utf8') as invoice_file:
        return ET.parse(input_file).getroot()

这可以很好地工作,并且我可以创建函数来处理数据而不会出现问题。但是当我试图在一个类中做同样的事情时,我得到了一个错误信息:

代码语言:javascript
复制
xml.etree.ElementTree.ParseError: no element found: line 1, column 0

我认为这意味着解析器永远不会有任何东西需要解析,尽管我可能是错的。

类:

代码语言:javascript
复制
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()

创建类实例:

代码语言:javascript
复制
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')

非常感谢您的帮助。

EN

回答 2

Stack Overflow用户

发布于 2020-07-30 19:45:56

该错误表示invoice.xml为空,不包含XML或在XML数据之前包含XML +。

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 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)将指针重置回文件的开头:

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63172379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档