Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Parsing XML ด้วย DOM APIs ใน Python

Document Object Model (DOM) เป็น API แบบข้ามภาษาจาก W3C สำหรับเข้าถึงและแก้ไขเอกสาร XML DOM เหมาะสำหรับแอปพลิเคชันที่ต้องการเข้าถึงแบบสุ่ม (random-access) SAX อนุญาตให้เห็นเพียงส่วนเดียวของเอกสารในเวลาเดียวกัน

นี่คือวิธีที่ง่ายที่สุดในการโหลดเอกสาร XML และสร้างอ็อบเจ็กต์ minidom โดยใช้โมดูล xml.dom อ็อบเจ็กต์ minidom มีเมธอด parser แบบง่ายที่สร้าง DOM tree จากไฟล์ XML ได้อย่างรวดเร็ว

#!/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

ผลลัพธ์ตัวอย่าง

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

สำหรับรายละเอียด DOM API เต็มรูปแบบ โปรดอ้างอิงเอกสาร Python API มาตรฐาน