python 读取xml文件内容
时间: 2023-10-17 08:13:53 浏览: 163
可以使用Python内置的minidom模块来读取和解析XML文件内容。具体可以参考以下代码示例:
```python
from xml.dom import minidom
# 打开xml文件,获取dom对象
dom = minidom.parse('example.xml')
# 获取根节点
root_node = dom.documentElement
# 获取节点列表
books = root_node.getElementsByTagName('book')
# 遍历节点列表,获取节点属性和文本内容
for book in books:
print(f'Book ID: {book.getAttribute("id")}')
print(f'Book Title: {book.getElementsByTagName("title")[0].childNodes[0].data}')
print(f'Book Author: {book.getElementsByTagName("author")[0].childNodes[0].data}')
```
PS:这里的example.xml是一个样例XML文件,可以根据实际需要替换成自己的XML文件名。
相关问题
python 读取xml文件
Python有许多用于读取XML文件的模块,其中最常用的是`ElementTree`模块。
以下是一个简单的例子,演示如何使用`ElementTree`模块读取XML文件:
```python
import xml.etree.ElementTree as ET
# 解析XML文件
tree = ET.parse('example.xml')
# 获取根元素
root = tree.getroot()
# 遍历XML文件并打印元素和其文本内容
for elem in root.iter():
print(elem.tag, elem.text)
```
在上面的例子中,我们首先使用`ET.parse()`方法解析XML文件。然后,我们使用`tree.getroot()`方法获取根元素,并使用`root.iter()`方法遍历XML文件中的所有元素。最后,我们打印每个元素的标签和文本内容。
注意:在使用`ElementTree`模块读取XML文件时,如果XML文件中包含命名空间,则需要对元素标签进行命名空间处理。
python修改xml文件内容
可以使用Python的ElementTree模块来修改XML文件。以下是一个示例代码来修改XML文件中的元素内容:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('example.xml')
root = tree.getroot()
# 找到需要修改的元素
for child in root:
if child.attrib['name'] == 'element_name':
child.text = 'new_value'
# 保存修改后的XML文件
tree.write('example.xml')
```
在上面的代码中,我们首先使用`ET.parse()`方法来解析XML文件,然后使用`getroot()`方法获取根元素。接着,我们使用循环遍历根元素的所有子元素,找到需要修改的元素,然后修改元素的文本内容。最后,我们使用`write()`方法将修改后的XML文件保存回磁盘。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)