使用LXML ETREE在Python上解析本地机器上的XML文件时出现问题

时间:2014-03-21 20:50:26

标签: python xml lxml

我在Mac OSX上使用Python 2.7.3并安装了lxml版本3.3.3。我有几个位于同一目录中的xml文件,例如MyDir/file1.xmlMyDir/file2.xml。我试图将每个人带入python并提取相关信息。但是,我似乎无法让etree解析器工作。我的代码非常简单:

 from lxml import etree
 from os import listdir
 from os.path import isfile, join

 xmlfiles = [x for x in listdir("MyDir") if isfile(join("MyDir",x))]

 for file in xmlfiles:

     doc = etree.parse(file)

         get the stuff I need

但是,解析器不断向我发出以下错误

 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "lxml.etree.pyx", line 3239, in lxml.etree.parse (src/lxml/lxml.etree.c:69955)
   File "parser.pxi", line 1748, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:102066)
   File "parser.pxi", line 1774, in lxml.etree._parseDocumentFromURL       
   (src/lxml/lxml.etree.c:102330)
   File "parser.pxi", line 1678, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:101365)
   File "parser.pxi", line 1110, in lxml.etree._BaseParser._parseDocFromFile 
   (src/lxml/lxml.etree.c:96817)
   File "parser.pxi", line 582, in lxml.etree._ParserContext._handleParseResultDoc   
   (src/lxml/lxml.etree.c:91275)
   File "parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:92461)
   File "parser.pxi", line 620, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:91722)
 IOError: Error reading file 'File1.xml': failed to load external entity     
 "File1.xml"

我已经在这里查看了几个答案,但它们都是针对特定问题的,主要是处理将解析器提供给html文件而我只是将它提供给已存储在本地计算机上的xml文件。有人可以帮我弄清楚为什么这不能正常工作吗?

此外,有没有更好的方法使用python从xml文件中解析和提取信息,然后采用我采用的方法(假设我让它工作!)。

由于

2 个答案:

答案 0 :(得分:1)

我最好使用带有*.xml文件掩码的glob.iglob()。这更加明确和安全:

for filename in glob.iglob("MyDir/*.xml"):
    tree = etree.parse(filename)
    print tree.getroot()

希望有所帮助。

答案 1 :(得分:1)

您没有提供完整的文件路径,因此尝试加载文件失败。

您有几个选择:

  1. 在启动脚本(脆弱)之前从shell更改为MyDir
  2. 在脚本中,在MyDir循环之前更改为for(例如import os;' os.chdir('MyDir')
  3. 在列表推导中包含完整路径,例如:

    xmlfiles = [join("MyDir",x) for x in listdir("MyDir") if isfile(join("MyDir",x))]
    
  4. 在for循环中构建路径,例如:

    for file in xmlfiles:
        doc = etree.parse(join("MyDir",file))
        #continue on
    
  5. 显然有其他解决方案,例如@ alecxe是他使用glob的迭代器(使用路径返回文件,而不是os.listdir()的文件名)。