【问题标题】:Trouble Using LXML ETREE to Parse XML Files on Local Machine With Python使用 LXML ETREE 在本地机器上使用 Python 解析 XML 文件时遇到问题
【发布时间】:2014-04-29 10:36:37
【问题描述】:

我在 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 文件中解析和提取信息,然后是我正在采用的方法(假设我让它工作!)。

谢谢

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

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

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

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

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

      你有几个选择:

      1. 在启动脚本之前从 shell 更改为 MyDir(脆弱)
      2. 在脚本中,在 for 循环之前更改为 MyDir(例如 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
        

      显然还有其他解决方案,例如@alecxe 使用 glob 的迭代器(它返回带有路径的文件,而不仅仅是 os.listdir() 的文件名)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        • 2014-03-27
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多