简体   繁体   中英

Python ElementTree “no element found” exception

imports:

import io
import xml.etree.ElementTree as ElementTree

NOTE : I've looked at other threads on this same exception, and they all mentioned that a potential problem is that the XML file could be malformed; I'm extremely certain mine is well formed, after checking it multiple times, then ran it through an online validator just to double check.

Basically, I'm having trouble calling Python's ElementTree.parse() function on an io.StringIO file object. I know this operation works, because the following code, which is directly above the problem code, works:

testXMLInput = io.StringIO("<timedmile><miles>1</miles><minutes>1</minutes><seconds>1</seconds><month>1</month><day>1</day><year>1</year></timedmile>")
myElementTree = ElementTree.parse(testXMLInput)

However, the following code doesn't work:

xmlOutput = io.StringIO("<logdata><timedmiles></timedmiles></logdata>")
testElementTree = ElementTree.parse(xmlOutput)

I tried putting a value in the timedmiles element, but that didn't stop the following exception from being raised:

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

What could the problem be? The documentation and other threads don't seem to mention another cause of this exception.

Maybe you use some outdated version of ElementTree?

Run ElementTree.VERSION to get the version.

I use version 1.3.0 and didn't get your error (in both cases). Maybe you should upgrade your software?

I have also another remark: After you parse a source file, the result is of ElementTree type. But to perform various operations, you should then run root = myElementTree.getroot() (this time the result is of Element type) and use just this root element.

Eg if you run ElementTree.tostring(...) , the first parameter should be just root , not myElementTree .

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