怎么读取xml配置文件
时间: 2023-09-27 11:03:58 浏览: 37
读取 XML 配置文件的方法有很多种,以下是一种使用 Python 中的 ElementTree 库来读取 XML 配置文件的示例代码:
```python
import xml.etree.ElementTree as ET
# 解析 XML 文件
tree = ET.parse('config.xml')
# 获取根元素
root = tree.getroot()
# 遍历根元素下的所有子元素
for child in root:
# 打印子元素的标签和文本内容
print(child.tag, child.text)
```
上述代码中,首先使用 `ET.parse()` 方法解析 XML 文件,然后使用 `tree.getroot()` 方法获取根元素。接着,使用 `for` 循环遍历根元素下的所有子元素,并打印子元素的标签和文本内容。
需要注意的是,以上代码假设 XML 文件的格式类似于以下示例:
```xml
<config>
<database>
<host>localhost</host>
<port>3306</port>
<username>root</username>
<password>123456</password>
<database>test_db</database>
</database>
<server>
<host>127.0.0.1</host>
<port>8080</port>
<timeout>60</timeout>
</server>
</config>
```
如果你的 XML 文件格式不同,可能需要做出相应的修改。