Computer >> Máy Tính >  >> Lập trình >> Python

Phân tích cú pháp XML với các API DOM bằng Python

Mô hình Đối tượng Tài liệu ("DOM") là một API đa ngôn ngữ từ World Wide Web Consortium (W3C) để truy cập và sửa đổi các 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 bạn xem từng bit 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 có quyền truy cập vào phần tử khác.

Đây là cách dễ nhất để tải nhanh một tài liệu XML và tạo một đối tượng minidom bằng cách sử dụng mô-đun xml.dom. Đối tượng minidom cung cấp một phương thức phân tích cú pháp đơn giản để nhanh chóng tạo một cây DOM từ tệp XML.

Cụm từ mẫu gọi hàm phân tích cú pháp (tệp [, trình phân tích cú pháp]) của đối tượng minidom để phân tích cú pháp tệp XML được tệp chỉ định thành đối tượng cây DOM.

#!/usr/bin/python
from xml.dom.minidom import parse
import xml.dom.minidom
# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
   print "Root element : %s" % collection.getAttribute("shelf")
# Get all the movies in the collection
movies = collection.getElementsByTagName("movie")
# Print detail of each movie.
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

Điều này sẽ tạo ra 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 các API Python tiêu chuẩn.