简体   繁体   English

Python ElementTree“找不到元素”异常

[英]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;注意:我已经查看了有关同一异常的其他线程,他们都提到一个潜在的问题是 XML 文件可能格式错误; 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.基本上,我无法在 io.StringIO 文件 object 上调用 Python 的 ElementTree.parse() function。 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:我尝试在 timedmiles 元素中放置一个值,但这并没有阻止引发以下异常:

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?也许您使用了一些过时的 ElementTree 版本?

Run ElementTree.VERSION to get the version.运行ElementTree.VERSION以获取版本。

I use version 1.3.0 and didn't get your error (in both cases).我使用版本1.3.0并且没有收到您的错误(在这两种情况下)。 Maybe you should upgrade your software?也许你应该升级你的软件?

I have also another remark: After you parse a source file, the result is of ElementTree type.我还有一句话:解析源文件后,结果是ElementTree类型。 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.但是要执行各种操作,您应该运行root = myElementTree.getroot() (这次结果是Element类型)并只使用这个元素。

Eg if you run ElementTree.tostring(...) , the first parameter should be just root , not myElementTree .例如,如果您运行ElementTree.tostring(...) ,第一个参数应该只是root ,而不是myElementTree

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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