2015-02-10 104 views
1

我是一個Python新手,最近一直在使用它來嘗試解析大型xml文件700mb。Python使用xml iterparse從大型xml文件中移除元素

環顧四周,我一直在嘗試使用iterparse方法來爲XML刪除名爲Revision_History的元素,因爲我們不再需要這些信息。

我已經通過這個腳本的幾個變化,所以它現在可能是可怕的錯誤。對於前兩個清除似乎工作正常。然而,它然後停止工作,並沒有發現更多的revision_history標籤。

import xml.etree.ElementTree as ET 
for event, elem in ET.iterparse("AAT.xml", events=("end",)): 
if event == "end": 
    for subject in elem.findall ("{http://localhost/namespace}Subject"): 
     print ("subject found") 
     for revision in subject.findall("("{http://localhost/namespace}Revision_History"): 
      print ("revision found") 
      subject.remove (revision) 
      print ("done") 
    elem.clear() 

任何建議非常感謝!

亞當

+0

看起來像「如果事件== ..」有一個錯誤的縮進,所以看起來沒有任何運行在你的循環中,你有這種格式的任何語法錯誤? – artemdevel 2015-02-10 11:05:25

+0

artemdevel,這是我粘貼它的錯誤。 – ADWALSH 2015-02-10 16:14:16

回答

1

嘗試使用cElementTree而不是ElementTree。它已經顯著我快,但我從來沒有解析文件,你正在分析

from xml.etree import cElementTree as ET 

其次尺寸,試穿匹配的元素用iterfind()代替findall()

from xml.etree import cElementTree as ET 

for event, elem in ET.iterparse("books.xml", events=("end",)): 
    if elem.tag == "book": 
     for d in elem.iterfind("description"): 
      elem.remove(d) 

第三,這取決於你想要多少RAM使用,你可以嘗試使用XPath查找哪有你要刪除的子元素。然後,重複父母,刪除這些孩子。非常差例如:

for event, elem in ET.iterparse("books.xml", events=("end",)): 
    for book_with_desc in elem.iterfind(".//Subject[Revision_History]"): 
     for child in book_with_desc: 
      if child.tag == "Revision_History": 
       remove(child) 

在XPath,儘量避免.//foo路徑,如果你知道你的文檔的結構,譜寫更加高效的查詢,如./path/to/element/foo[@attr=bar]或相似。

我敢肯定,有很多更好的方法來解決這個問題。