打开文件时lxml中的隐秘错误

时间:2016-07-18 07:15:40

标签: python python-2.7 debugging error-handling lxml

我的代码很简单;

f = open(r"C:\filepath\file.xml")
xml = f.read()
tree = etree.parse(xml)

运行时,我得到堆栈跟踪

tree = etree.parse(xml)
  File "src/lxml/lxml.etree.pyx", line 3427, in lxml.etree.parse (src\lxml\lxml.etree.c:79801)
  File "src/lxml/parser.pxi", line 1782, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:115995)
  File "src/lxml/parser.pxi", line 1808, in lxml.etree._parseDocumentFromURL (src\lxml\lxml.etree.c:116345)
  File "src/lxml/parser.pxi", line 1712, in lxml.etree._parseDocFromFile (src\lxml\lxml.etree.c:115233)
  File "src/lxml/parser.pxi", line 1115, in lxml.etree._BaseParser._parseDocFromFile (src\lxml\lxml.etree.c:109930)
  File "src/lxml/parser.pxi", line 573, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:103404)
  File "src/lxml/parser.pxi", line 683, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:105058)
  File "src/lxml/parser.pxi", line 611, in lxml.etree._raiseParseError (src\lxml\lxml.etree.c:103924)
IOError

这里发生了什么?

1 个答案:

答案 0 :(得分:1)

parse()接受XML文件的路径:

tree = etree.parse(r"C:\filepath\file.xml")

目前,您的代码会将XML的实际内容传递给parse(),这将触发此类IOError。您可以使用fromstring()来创建包含实际XML数据的字符串的Element对象。如果需要,您可以从之前创建的ElementTree

创建Element对象
f = open(r"C:\filepath\file.xml")
xml = f.read()
root = etree.fromstring(xml)
tree = etree.ElementTree(root)