使用 Expat 在 Python 中快速解析 XML
Python 允許透過內建的 expat 模組讀取和處理 XML 資料。它是一個非驗證 XML 解析器。它建立一個 XML 解析器物件,並將它的物件屬性捕獲到各種處理函式中。在以下示例中,我們將看到各種處理函式如何幫助我們讀取 XML 檔案以及將屬性值作為輸出資料。生成的這些資料可用於處理。
示例
import xml.parsers.expat # Capture the first element def first_element(tag, attrs): print ('first element:', tag, attrs) # Capture the last element def last_element(tag): print ('last element:', tag) # Capture the character Data def character_value(value): print ('Character value:', repr(value)) parser_expat = xml.parsers.expat.ParserCreate() parser_expat.StartElementHandler = first_element parser_expat.EndElementHandler = last_element parser_expat.CharacterDataHandler = character_value parser_expat.Parse(""" <?xml version="1.0"?> <parent student_rollno="15"> <child1 Student_name="Krishna"> Strive for progress, not perfection</child1> <child2 student_name="vamsi"> There are no shortcuts to any place worth going</child2> </parent>""", 1)
輸出
執行以上程式碼將產生以下結果 −
first element: parent {'student_rollno': '15'} Character value: '\n' first element: child1 {'Student_name': 'Krishna'} Character value: 'Strive for progress, not perfection' last element: child1 Character value: '\n' first element: child2 {'student_name': 'vamsi'} Character value: ' There are no shortcuts to any place worth going' last element: child2 Character value: '\n' last element: parent
Advertisement