SAX là giao diện chuẩn cho phân tích XML dựa trên sự kiện. Phân tích XML với SAX thường yêu cầu bạn tạo ContentHandler riêng bằng cách kế thừa từ xml.sax.ContentHandler.
ContentHandler của bạn xử lý các thẻ và thuộc tính đặc thù của loại XML của bạn. Đối tượng ContentHandler cung cấp các phương thức để xử lý nhiều sự kiện phân tích. Trình phân tích sở hữu nó gọi các phương thức của ContentHandler khi nó phân tích tệp XML.
Các phương thức startDocument và endDocument được gọi ở đầu và cuối tệp XML. Phương thức characters(text) nhận dữ liệu ký tự của tệp XML qua tham số text.
ContentHandler được gọi tại đầu và cuối mỗi phần tử. Nếu trình phân tích không ở chế độ namespace, các phương thức startElement(tag, attributes) và endElement(tag) được gọi; ngược lại, các phương thức startElementNS và endElementNS được gọi. Ở đây, tag là thẻ phần tử, và attributes là đối tượng Attributes.
Dưới đây là các phương thức quan trọng khác cần hiểu trước khi tiếp tục:
Phương thức make_parser
Phương thức sau tạo một đối tượng trình phân tích mới và trả về nó. Đối tượng trình phân tích được tạo sẽ là loại trình phân tích đầu tiên mà hệ thống tìm thấy.
xml.sax.make_parser([parser_list])
Chi tiết tham số:
- parser_list - Danh sách tùy chọn các trình phân tích để sử dụng, tất cả phải triển khai phương thức
make_parser.
Phương thức parse
Phương thức sau tạo một trình phân tích SAX và sử dụng nó để phân tích một tài liệu.
xml.sax.parse(xmlfile, contenthandler[, errorhandler])
Chi tiết tham số:
- xmlfile - Tên tệp XML để đọc.
- contenthandler - Phải là đối tượng
ContentHandler. - errorhandler - Nếu chỉ định, phải là đối tượng
SAX ErrorHandler.
Phương thức parseString
Có thêm một phương thức để tạo trình phân tích SAX và phân tích chuỗi XML được chỉ định.
xml.sax.parseString(xmlstring, contenthandler[, errorhandler])
Chi tiết tham số:
- xmlstring - Chuỗi XML để đọc.
- contenthandler - Phải là đối tượng
ContentHandler. - errorhandler - Nếu chỉ định, phải là đối tượng
SAX ErrorHandler.
Ví dụ
#!/usr/bin/python
import xml.sax
class MovieHandler(xml.sax.ContentHandler):
def __init__(self):
self.CurrentData = ""
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""
# Gọi khi một phần tử bắt đầu
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
print "*****Movie*****"
title = attributes["title"]
print "Title:", title
# Gọi khi một phần tử kết thúc
def endElement(self, tag):
if self.CurrentData == "type":
print "Type:", self.type
elif self.CurrentData == "format":
print "Format:", self.format
elif self.CurrentData == "year":
print "Year:", self.year
elif self.CurrentData == "rating":
print "Rating:", self.rating
elif self.CurrentData == "stars":
print "Stars:", self.stars
elif self.CurrentData == "description":
print "Description:", self.description
self.CurrentData = ""
# Gọi khi đọc ký tự
def characters(self, content):
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content
if (__name__ == "__main__"):
# Tạo XMLReader
parser = xml.sax.make_parser()
# Tắt namespaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# Ghi đè ContextHandler mặc định
Handler = MovieHandler()
parser.setContentHandler(Handler)
parser.parse("movies.xml")
Đoạn mã trên cho kết quả sau:
*****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Year: 2003 Rating: PG Stars: 10 Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Year: 1989 Rating: R Stars: 8 Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Stars: 10 Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Stars: 2 Description: Viewable boredom
Để biết chi tiết đầy đủ về tài liệu API SAX, vui lòng tham khảo tài liệu Python SAX APIs chuẩn.