Mô hình đối tượng tài liệu (DOM) là một API đa ngôn ngữ từ Hiệp hội World Wide Web (W3C) để truy cập và sửa đổi tài liệu XML.
DOM cực kỳ hữu ích cho các ứng dụng truy cập ngẫu nhiên. SAX chỉ cho phép xem một phần của tài liệu tại một thời điểm. Nếu bạn đang xem một phần tử SAX, bạn không thể truy cập phần tử khác.
Dưới đây là cách dễ nhất để nhanh chóng tải một tài liệu XML và tạo đối tượng minidom sử dụng mô-đun xml.dom. Đối tượng minidom cung cấp phương thức phân tích cú pháp đơn giản, nhanh chóng tạo cây DOM từ tệp XML.
Câu lệnh mẫu gọi hàm parse(file[, parser]) của đối tượng minidom để phân tích tệp XML được chỉ định bởi file thành đối tượng cây DOM.
#!/usr/bin/python
from xml.dom.minidom import parse
import xml.dom.minidom
# Mở tài liệu XML sử dụng trình phân tích minidom
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
print "Root element : %s" % collection.getAttribute("shelf")
# Lấy tất cả phim trong tập hợp
movies = collection.getElementsByTagName("movie")
# In chi tiết từng phim
for movie in movies:
print "*****Movie*****"
if movie.hasAttribute("title"):
print "Title: %s" % movie.getAttribute("title")
type = movie.getElementsByTagName('type')[0]
print "Type: %s" % type.childNodes[0].data
format = movie.getElementsByTagName('format')[0]
print "Format: %s" % format.childNodes[0].data
rating = movie.getElementsByTagName('rating')[0]
print "Rating: %s" % rating.childNodes[0].data
description = movie.getElementsByTagName('description')[0]
print "Description: %s" % description.childNodes[0].data
Đoạn mã trên sẽ cho kết quả sau:
Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Rating: R Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Description: Viewable boredom
Để biết chi tiết đầy đủ về tài liệu API DOM, vui lòng tham khảo tài liệu API Python chuẩn.