Python cho phép dữ liệu XML được đọc và xử lý thông qua mô-đun built-in tên là expat. Đây là trình phân tích XML không xác thực (non-validating). Nó tạo đối tượng XML parser và bắt các thuộc tính của đối tượng vào các hàm xử lý (handler functions) khác nhau. Trong ví dụ dưới đây, chúng ta sẽ thấy cách các hàm xử lý giúp đọc file XML cũng như đưa ra giá trị thuộc tính làm dữ liệu đầu ra. Dữ liệu sinh ra này có thể dùng cho xử lý tiếp theo.
Ví dụ
import xml.parsers.expat
# Bắt phần tử đầu tiên
def phan_tu_dau(ten, thuoc_tinh):
print('Phần tử đầu:', ten, thuoc_tinh)
# Bắt phần tử cuối
def phan_tu_cuoi(ten):
print('Phần tử cuối:', ten)
# Bắt dữ liệu ký tự
def du_lieu_ky_tu(gia_tri):
print('Dữ liệu ký tự:', repr(gia_tri))
parser_expat = xml.parsers.expat.ParserCreate()
parser_expat.StartElementHandler = phan_tu_dau
parser_expat.EndElementHandler = phan_tu_cuoi
parser_expat.CharacterDataHandler = du_lieu_ky_tu
parser_expat.Parse("""
Strive for progress, not perfection
There are no shortcuts to any place worth going
""", 1)
Kết quả
Chạy mã trên cho kết quả sau:
Phần tử đầu: parent {'student_rollno': '15'}
Dữ liệu ký tự: '\n'
Phần tử đầu: child1 {'Student_name': 'Krishna'}
Dữ liệu ký tự: 'Strive for progress, not perfection'
Phần tử cuối: child1
Dữ liệu ký tự: '\n'
Phần tử đầu: child2 {'student_name': 'vamsi'}
Dữ liệu ký tự: ' There are no shortcuts to any place worth going'
Phần tử cuối: child2
Dữ liệu ký tự: '\n'
Phần tử cuối: parent