简体   繁体   中英

'xml.etree.ElementTree.ParseError: no element found' when making python class

I'm trying to make a class which makes it easier to handle XML-invoices, but I am having trouble getting ElementTree to work within a class.

This is the general idea of what I'm trying to do:

def open_invoice(input_file):
    with open(input_file, 'r', encoding = 'utf8') as invoice_file:
        return ET.parse(input_file).getroot()

This works fine, and I can make functions to handle the data without issue. But when trying to do the equivalent inside a class, I get an error message:

xml.etree.ElementTree.ParseError: no element found: line 1, column 0

I think this means that the parser is never given anything to parse, though I could be wrong.

The class:

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()

Making the class instance:

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')

Help is much appreciated.

The error means that invoice.xml is empty, does not contain XML or contains XML + over stuff before the XML data.

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

The problem here is that you are attempting to read the contents of the file peppol_invoice twice, once in the call to xmltodict.parse , and once in the call to ET.parse .

After the call to peppol_invoice.read() completes, peppol_invoice is left pointing at the end of the file. You get the error in your question title because when peppol_invoice is passed to ET.parse , there is nothing left to be read from the file.

If you want to read the contents of the file again, call peppol_invoice.seek(0) to reset the pointer back to the start of the file:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM