# 定义一个 XML 字符串
xml_string ='''
<bookstore>
<book>
<title>Introduction to Python</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>Data Science with Python</title>
<author>Jane Smith</author>
<price>39.95</price>
</book>
</bookstore>
'''
# 使用 ElementTree 解析 XML 字符串
root = ET.fromstring(xml_string)
# 遍历 XML 树 for book in root.findall('book'):
title = book.find('title').text
author = book.find('author').text
price = book.find('price').text print(f'Title: {title}, Author: {author}, Price: {price}')
以上代码执行输出结果为:
Title:Introduction to Python,Author:JohnDoe,Price:29.99Title:DataSciencewithPython,Author:JaneSmith,Price:39.95
class MovieHandler(xml.sax.ContentHandler): def__init__(self): self.CurrentData="" self.type="" self.format="" self.year="" self.rating="" self.stars="" self.description=""
# 元素开始调用 def startElement(self, tag, attributes): self.CurrentData= tag if tag =="movie": print("*****Movie*****")
title = attributes["title"] print("Title:", title)
*****Movie*****Title:EnemyBehindType:War,ThrillerFormat: DVD
Year:2003Rating: PG
Stars:10Description:Talk about a US-Japan war
*****Movie*****Title:TransformersType:Anime,ScienceFictionFormat: DVD
Year:1989Rating: R
Stars:8Description: A schientific fiction
*****Movie*****Title:TrigunType:Anime,ActionFormat: DVD
Rating: PG
Stars:10Description:Vash the Stampede!*****Movie*****Title:IshtarType:ComedyFormat: VHS
Rating: PG
Stars:2Description:Viewable boredom
Root element :NewArrivals*****Movie*****Title:EnemyBehindType:War,ThrillerFormat: DVD
Rating: PG
Description:Talk about a US-Japan war
*****Movie*****Title:TransformersType:Anime,ScienceFictionFormat: DVD
Rating: R
Description: A schientific fiction
*****Movie*****Title:TrigunType:Anime,ActionFormat: DVD
Rating: PG
Description:Vash the Stampede!*****Movie*****Title:IshtarType:ComedyFormat: VHS
Rating: PG
Description:Viewable boredom