Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xử lý XML trong Python với ElementTree và DOM

Mô tả

Python cung cấp 2 cách chính parse XML: ElementTree (nhẹ, Pythonic) và DOM (tiêu chuẩn W3C, nặng hơn).

File XML mẫu (tutorials.xml)

<?xml version="1.0"?>
<Tutorials>
  <Tutorial id="Tu101">
    <author>Vicky, Matthew</author>
    <title>Geo-Spatial Data Analysis</title>
    <stream>Python</stream>
    <price>4.95</price>
    <publish_date>2020-07-01</publish_date>
    <description>Learn geo Spatial data Analysis using Python.</description>
  </Tutorial>
  <Tutorial id="Tu102">
    <author>Bolan, Kim</author>
    <title>Data Structures</title>
    <stream>Computer Science</stream>
    <price>12.03</price>
    <publish_date>2020-1-19</publish_date>
    <description>Learn Data structures using different programming languages.</description>
  </Tutorial>
  <Tutorial id="Tu103">
    <author>Sora, Everest</author>
    <title>Analytics using Tensorflow</title>
    <stream>Data Science</stream>
    <price>7.11</price>
    <publish_date>2020-1-19</publish_date>
    <description>Learn Data analytics using Tensorflow.</description>
  </Tutorial>
</Tutorials>

1. ElementTree (Khuyên dùng)

Đọc toàn bộ nội dung

import xml.etree.ElementTree as ET

tree = ET.parse('tutorials.xml')
root = tree.getroot()

print("Danh sách Tutorial:")
for tutorial in root:
    print(f"\n--- Tutorial {tutorial.attrib.get('id')} ---")
    for child in tutorial:
        print(f"  {child.tag}: {child.text}")

Lấy attribute

for tutorial in root.iter('Tutorial'):
    print(tutorial.attrib)  # {'id': 'Tu101'}

Lọc với XPath (findall)

# Tìm Tutorial có price = 12.03
for tutorial in root.findall("./Tutorial[price='12.03']"):
    print(tutorial.attrib)  # {'id': 'Tu102'}

# Tìm tất cả title
titles = root.findall('.//title')
for t in titles:
    print(t.text)

Tạo/Sửa XML

# Tạo mới
new_tut = ET.SubElement(root, 'Tutorial', id='Tu104')
ET.SubElement(new_tut, 'title').text = 'New Tutorial'
ET.SubElement(new_tut, 'price').text = '9.99'

# Ghi file
tree.write('tutorials_updated.xml', encoding='utf-8', xml_declaration=True)

2. DOM API (xml.dom.minidom)

from xml.dom.minidom import parse

DOMTree = parse('tutorials.xml')
collection = DOMTree.documentElement

tutorials = collection.getElementsByTagName("Tutorial")
for tut in tutorials:
    stream = tut.getElementsByTagName('stream')[0]
    price = tut.getElementsByTagName('price')[0]
    print(f"Stream: {stream.childNodes[0].data}, Price: {price.childNodes[0].data}")

So sánh

Đặc điểmElementTreeDOM
Bộ nhớTải toàn bộ treeTải toàn bộ tree
APIPythonic, đơn giảnW3C DOM standard, phức tạp
XPathHỗ trợ cơ bản (findall)Không có sẵn
Hiệu năngNhanh hơnChậm hơn
Khuyên dùngCóChỉ khi cần tương thích DOM

3. Xử lý XML lớn: iterparse (Streaming)

# Cho file XML rất lớn, không load hết vào RAM
for event, elem in ET.iterparse('large_file.xml', events=('start', 'end')):
    if event == 'end' and elem.tag == 'Tutorial':
        # Xử lý elem
        print(elem.find('title').text)
        # Quan trọng: clear để giải phóng bộ nhớ
        elem.clear()