1. 程式人生 > >python讀取xml檔案報錯xml.parsers.expat.ExpatError: XML or text declaration not at start of entity

python讀取xml檔案報錯xml.parsers.expat.ExpatError: XML or text declaration not at start of entity

先說明一下我之前對python的xml.dom.minidom模組不熟,遇到這個問題時先想到的是百度,結果轉了一圈回來發現大家都寫的是xml檔案中的第一行,也就是

<?xml version="1.0" encoding="GBK"?>

這個可能沒有頂格寫,有空格。可是我遇到的問題是,它確實是在第一行第一列寫的,然後,我就反覆去看xml檔案,發現了檔案中間還有一個<?xml version="1.0"?>標籤,導致了報錯。所以並不是我們寫的程式碼有問題,只能說是程式碼寫得不完善。

所以我的解決辦法是直接在讀取檔案時寫了一個異常處理,當發現錯誤格式的Xml檔案時就記錄這個檔案,並跳過它,執行下一個xml檔案。

#開啟xml文件,並返回dom物件
def read_init(path):
    dom = xml.dom.minidom.parse(path)
    return dom

#開啟xml文件,並返回根節點
def root_back(dom):
    root = dom.documentElement
    return root

for ele in file_list:
    try:
        root =  root_back(read_init(path+"/"+ele.name))
    except xml.parsers.expat.ExpatError:
unread_file.append(ele) continue