python如何解析xml文件,举个例子
时间: 2024-02-18 18:59:17 浏览: 69
Python中可以使用标准库中的xml.etree.ElementTree模块来解析XML文件。这个模块提供了一些简单的API来处理XML文件,包括解析XML文件、遍历XML文档、读取和修改XML元素等等。
下面是一个简单的例子,它演示了如何使用ElementTree模块来解析一个XML文件,并读取其中的元素。
假设我们有一个名为example.xml的XML文件,它的内容如下:
```xml
<?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,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
```
我们可以使用ElementTree模块来解析这个XML文件,代码如下:
```python
import xml.etree.ElementTree as ET
# 解析XML文件
tree = ET.parse('example.xml')
# 获取根节点
root = tree.getroot()
# 遍历XML文档
for child in root:
print(child.tag, child.attrib)
# 遍历子节点
for sub_child in child:
print(sub_child.tag, sub_child.text)
```
运行上述代码,输出如下:
```
catalog {}
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,
an evil sorceress, and her own childhood to become queen
of the world.
```
上述代码首先使用ET.parse()方法解析了example.xml文件,并获取了XML文件的根节点。然后,我们使用for循环遍历XML文档中的每个元素,并输出它们的标签和属性。最后,我们使用另一个for循环遍历每个元素的子元素,并输出它们的标签和文本。
阅读全文
相关推荐


















