在Python中解析XML,可以使用ElementTree库。ElementTree是Python内置的库,可以方便地解析XML文档。以下是一个使用ElementTree解析XML的示例:
import xml.etree.ElementTree as ET
# 定义XML文档
xml_data = '''<?xml version="1.0"?><catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<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>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies and an evil sorceress.</description>
</book>
</catalog>
'''
# 解析XML文档
root = ET.fromstring(xml_data)
# 获取所有的book元素
books = root.findall('book')
# 遍历所有的book元素
for book in books:
# 获取book元素的属性
book_id = book.get('id')
print(f"Book ID: {book_id}")
# 获取book元素的子元素
author = book.find('author').text
title = book.find('title').text
genre = book.find('genre').text
price = book.find('price').text
publish_date = book.find('publish_date').text
description = book.find('description').text
# 输出book元素的子元素
print(f"Author: {author}")
print(f"Title: {title}")
print(f"Genre: {genre}")
print(f"Price: {price}")
print(f"Publish Date: {publish_date}")
print(f"Description: {description}")
print()
运行上述代码,将输出以下结果:
Book ID: bk101
Author: Gambardella, Matthew
Title: XML Developer's Guide
Genre: Computer
Price: 44.95
Publish Date: 2000-10-01
Description: An in-depth look at creating applications with XML.
Book ID: bk102
Author: Ralls, Kim
Title: Midnight Rain
Genre: Fantasy
Price: 5.95
Publish Date: 2000-12-16
Description: A former architect battles corporate zombies and an evil sorceress.
在这个示例中,我们使用ElementTree库解析了一个包含两个book元素的XML文档。我们首先定义了XML文档,然后使用fromstring方法将其解析为一个Element对象。接着,我们使用findall方法获取所有的book元素,并遍历它们。对于每个book元素,我们使用get方法获取其属性,使用find方法获取其子元素,并输出它们的值。
领取专属 10元无门槛券
手把手带您无忧上云