python 解析xml
时间: 2023-10-12 08:16:12 浏览: 38
Python有许多用于解析xml的库,其中最常用的是ElementTree库。以下是一个简单的例子:
```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)
# 访问xml元素
print("\nAccess elements:")
print('title:', root[0][0].text)
print('description:', root[0][1].text)
print('year:', root[0][2].text)
# 修改xml元素
root[0][2].text = '2021'
# 保存修改后的xml文件
tree.write('example.xml')
```
在上面的代码中,我们首先使用ET.parse()方法读取了一个名为example.xml的xml文件,并将其存储在tree对象中。然后,我们使用tree.getroot()方法获取xml文件的根元素,并进行遍历和访问元素的操作。最后,我们修改了xml文件中的一个元素,并使用tree.write()方法保存修改后的xml文件。
相关问题
Python解析XML
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并访问其中的数据了。
python解析xml
Python 解析 XML 可以使用标准库中的 `xml.etree.ElementTree` 模块。该模块提供了 Element 类,可以用来表示 XML 文档中的元素和属性。以下是一个简单的示例:
```python
import xml.etree.ElementTree as ET
# 加载 XML 文档
tree = ET.parse('example.xml')
# 获取根元素
root = tree.getroot()
# 遍历子元素
for child in root:
print(child.tag, child.attrib)
# 获取指定元素的文本内容
title = root.find('book/title').text
author = root.find('book/author').text
print(title, author)
```
在这个示例中,我们首先使用 `ET.parse()` 函数加载 XML 文档,然后使用 `getroot()` 方法获取根元素。接下来,我们使用 `for` 循环遍历根元素的子元素,并使用 `tag` 和 `attrib` 属性打印每个子元素的标签名和属性。最后,我们使用 `find()` 方法获取指定元素的文本内容,并打印出来。
除了 `find()` 方法,Element 对象还提供了其他访问元素和属性的方法,例如 `findall()`、`iter()`、`get()` 等,具体可以参考 Python 官方文档。