一、XML 簡介
XML(Extensible Markup Language)是一種類似於 HTML 的標記語言,它可以被用來存儲和傳輸數據。XML 可以表示複雜的數據類型,包括數組、對象、文本、數字等,這使得它在數據交換和儲存方面有很大的用處。
二、為什麼使用 Python 解析 XML?
使用 Python 解析 XML 有很多有益的原因。Python 是一種流行的編程語言,擁有很好的模塊系統。Python 擁有許多第三方模塊,其中有許多可以用來解析 XML 數據,例如 ElementTree 和 lxml 等。Python 還有一些內置的模塊可以用來處理 Xml 數據,例如 re 和 xml.dom.minidom 等。此外,Python 語言易於學習且語法簡潔,讓新手也可以快速上手。
三、使用 Python 解析 XML 的步驟
在 Python 中,解析 Xml 的步驟通常為以下幾步:
1、導入所需的庫和模塊:
import xml.etree.ElementTree as ET
2、打開並讀取 XML 文件:
tree = ET.parse('example.xml')
root = tree.getroot()
在這裡,我們使用 ElementTree 模塊中的 parse() 函數來打開 XML 文件,並將返回的樹存儲在變數 tree 中。root 屬性用於在之後訪問代碼中訪問 Xml 文件的根元素。
3、獲取 Xml 文件中的數據:
for child in root:
print(child.tag, child.attrib)
這將輸出所有子元素及其屬性的標籤。
4、修改 Xml 中的數據:
使用 ElementTree 模塊中的 set() 函數可以修改 Xml 元素的文本或屬性。例如:
tree = ET.parse('example.xml')
root = tree.getroot()
for element in root.iter('email'):
new_email = 'newaddress@example.com'
element.set('address', new_email)
tree.write('example.xml')
這將在所有 ’email’ 標籤中新建一個 ‘address’ 屬性,然後將它們的值設置為 ‘newaddress@example.com’。
四、使用 Python 解析 XML 的例子
在這裡,我們將使用 ElementTree 模塊以及上面所提到的步驟解析以下簡單的 XML:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
以下是用 Python 解析它的代碼:
import xml.etree.ElementTree as ET
tree = ET.parse('books.xml')
root = tree.getroot()
for book in root.findall('book'):
author = book.find('author').text
title = book.find('title').text
price = book.find('price').text
print("%s - %s, $%s" % (title, author, price))
這會輸出每本書的作者、標題和價格。
五、結論
在本文中,我們簡要介紹了如何使用 Python 解析 Xml 數據,以及使用在 Python 中操作 Xml 數據的優點。Python 和 Xml 都是非常出色的工具,它們可以非常好地相互結合使用。隨著 Xml 數據的使用越來越普遍,Python 解析 Xml 也越來越流行。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/285476.html