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

Mô-đun xử lý XML bằng Python

XML là viết tắt của "Ngôn ngữ đánh dấu có thể mở rộng". Nó chủ yếu được sử dụng trong các trang web, nơi dữ liệu có cấu trúc cụ thể. Nó có các phần tử, được xác định bởi một thẻ bắt đầu và một thẻ kết thúc. Thẻ là một cấu trúc đánh dấu bắt đầu bằng . Các ký tự giữa thẻ bắt đầu và thẻ kết thúc, là nội dung của phần tử. Các phần tử có thể chứa các phần tử khác, được gọi là "phần tử con".

Ví dụ

Dưới đây là ví dụ về tệp XML mà chúng tôi sẽ sử dụng trong hướng dẫn này.

<?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 lanuages.</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>

Đọc xml bằng xml.etree.ElementTree

Mô-đun này cung cấp quyền truy cập vào thư mục gốc của tệp xml và sau đó chúng ta có thể truy cập nội dung của các phần tử bên trong. Trong ví dụ dưới đây, chúng tôi sử dụng thuộc tính có tên là văn bản và lấy nội dung của các phần tử đó.

Ví dụ

import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for xml_elmt in xml_root:
   for inner_elmt in xml_elmt:
      print(inner_elmt.text)

Đầu ra

Chạy đoạn mã trên cho chúng ta kết quả sau -

Tutorial List :
Vicky, Matthew
Geo-Spatial Data Analysis
Python
4.95
2020-07-01
Learn geo Spatial data Analysis using Python.
Bolan, Kim
Data Structures
Computer Science
12.03
2020-1-19
Learn Data structures using different programming lanuages.
Sora, Everest
Analytics using Tensorflow
Data Science
7.11
2020-1-19
Learn Data analytics using Tensorflow.

Nhận các thuộc tính xml

Chúng ta có thể lấy danh sách các thuộc tính và giá trị của chúng trong thẻ gốc. Khi chúng tôi tìm thấy các thuộc tính, nó sẽ giúp chúng tôi điều hướng cây XML một cách dễ dàng.

Ví dụ

import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for movie in xml_root.iter('Tutorial'):
   print(movie.attrib)

Đầu ra

Chạy đoạn mã trên cho chúng ta kết quả sau -

Tutorial List :
{'id': 'Tu101'}
{'id': 'Tu102'}
{'id': 'Tu103'}

Kết quả lọc

Chúng ta cũng có thể lọc kết quả ra khỏi cây xml bằng cách sử dụng hàm findall () của mô-đun này. Trong ví dụ dưới đây, chúng tôi tìm ra id của hướng dẫn có giá là 12,03.

Ví dụ

import xml.etree.ElementTree as ET
xml_tree = ET.parse('E:\\TutorialsList.xml')
xml_root = xml_tree.getroot()
# Header
print('Tutorial List :')
for movie in xml_root.findall("./Tutorial/[price ='12.03']"):
   print(movie.attrib)

Đầu ra

Chạy đoạn mã trên cho chúng ta kết quả sau -

Tutorial List :
{'id': 'Tu102'}

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

Chúng tôi 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.

Ví dụ

from xml.dom.minidom import parse
import xml.dom.minidom

# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse('E:\\TutorialsList.xml')
collection = DOMTree.documentElement

# Get all the movies in the collection
tut_list = collection.getElementsByTagName("Tutorial")

print("*****Tutorials*****")
# Print details of each Tutorial.
for tut in tut_list:

   strm = tut.getElementsByTagName('stream')[0]
   print("Stream: ",strm.childNodes[0].data)

   prc = tut.getElementsByTagName('price')[0]
   print("Price: ", prc.childNodes[0].data)

Đầu ra

Chạy đoạn mã trên cho chúng ta kết quả sau -

*****Tutorials*****
Stream: Python
Price: 4.95
Stream: Computer Science
Price: 12.03
Stream: Data Science
Price: 7.11