Python解析XML
时间: 2024-03-30 16:32:24 浏览: 22
Python解析XML可以使用内置的xml.etree.ElementTree模块。该模块提供了一种简单而高效的方式来解析和操作XML数据。
首先,你需要导入xml.etree.ElementTree模块:
```
import xml.etree.ElementTree as ET
```
然后,你可以使用ET.parse()函数来解析XML文件,例如:
```
tree = ET.parse('example.xml')
```
接下来,你可以使用tree.getroot()方法获取XML文档的根元素,例如:
```
root = tree.getroot()
```
现在,你可以通过遍历根元素及其子元素来访问XML文档中的数据。例如,如果XML文档的结构如下所示:
```
<bookstore>
<book category="cooking">
<title lang="en">Italian Recipes</title>
<author>John Doe</author>
<year>2019</year>
<price>29.99</price>
</book>
<book category="programming">
<title lang="en">Python Programming</title>
<author>Jane Smith</author>
<year>2020</year>
<price>39.99</price>
</book>
</bookstore>
```
你可以使用以下代码来访问其中的数据:
```
for book in root:
title = book.find('title').text
author = book.find('author').text
year = book.find('year').text
price = book.find('price').text
print(f"Title: {title}, Author: {author}, Year: {year}, Price: {price}")
```
这样,你就可以解析XML并访问其中的数据了。