簡體   English   中英

使用ElementTree從文件夾中讀取多個xml文件

[英]Read multiple xml file from a folder using ElementTree

我對 Python 編碼非常陌生,並且幾個小時以來我一直試圖解決一個問題:

我有 1600 多個 xml 文件(0000.xml、0001.xml 等)需要解析才能進行文本挖掘項目。
但是出現了錯誤,當我有以下代碼時:

from os import listdir, path 
import xml.etree.ElementTree as ET

mypath = '../project/content' 
files = [f for f in listdir(mypath) if f.endswith('.xml')]

for file in files:    
    tree = ET.parse("../project/content/"+file)
    root = tree.getroot()

錯誤消息如下:

Traceback (most recent call last):

  File "/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-13-cdc3ee6c3989>", line 6, in <module>
    tree = ET.parse("../project/content/"+file)

  File "/anaconda3/lib/python3.6/xml/etree/ElementTree.py", line 1196, in parse
    tree.parse(source, parser)

  File "/anaconda3/lib/python3.6/xml/etree/ElementTree.py", line 597, in parse
    self._root = parser._parse_whole(source)

  File "<string>", line unknown ParseError: no element found: line 1, column 0

我在哪里犯了錯誤?

另外,我只想從每個 xml 文件的一個元素中提取文本,我只需將此行附加到代碼中就足夠了嗎? 此外,如何將每個結果保存到 txt 文件?

maintext = root.find("mainText").text

非常感謝!

創建路徑元素的正確方法是使用join:

在嘗試創建樹之前,將打印消息添加到代碼中。

您嘗試解析的XML是否有效?

解決解析問題后,即可使用多重處理功能來同時解析許多文件。

from os import listdir, path
import xml.etree.ElementTree as ET

mypath = '../project/content'
files = [path.join(mypath, f) for f in listdir(mypath) if f.endswith('.xml')]

for file in files:
    print(file)
    tree = ET.parse(file)
    root = tree.getroot()

我遇到類似的問題,嘗試一次性處理多個XML文件,我需要將處理后的文件存儲在JSON文件中。 我可以處理文件,但不能將整個內容存儲在JSON文件中。 它僅處理1個文件並將其存儲到JSON。 看起來ElementTree元素不是可迭代的? 任何援助將不勝感激。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM