python - python中的XML解析(xml.etree.ElementTree)
问题描述
我正在使用import xml.etree.ElementTree as ET在 python 中解析 xml 文件
我试过:
import xml.etree.ElementTree as ET
tree = ET.parse('pyxml.xml')
self.root = tree.getroot()
name=root[0][0].text
username=root[0][1].text
password=root[0][2].text
host=root[0][3].text
port=root[0][4].text
pyxml.xml:
<data>
<database>
<name>qwe</name>
<username>postgres</username>
<password>1234</password>
<host>localhost</host>
<port>5432</port>
</database>
</data>
但我想要 XML 文件,如:
<data>
<database name="abc" username="xyz" password="dummy" host="localhost" port="5432"/>
</data>
如果我这样做,root[0][0].text 不起作用。谁能告诉我如何访问它?
解决方案
试试下面的代码,
import xml.etree.ElementTree as ET
tree = ET.parse('/Users/a-8525/Documents/tmp/pyxml.xml')
root = tree.getroot()
database = root.find('database')
attribute = database.attrib
name = attribute['name']
username = attribute['username']
password =attribute['password']
host = attribute['host']
port = attribute['port']
推荐阅读
- intellij-idea - Dart SDK 在哪里?| 错误:指定为 Dart SDK home 的文件夹不存在
- javascript - 将图标附加到按钮
- sql-server - 从 SQL Server 按天提取数据
- android - 弹出软键盘时布局不调整
- java - 更新组件的高度也会改变它的宽度
- javascript - 我正在尝试将 javascript Number 类型转换为 BIGINT 以传递给 Postgres 表
- php - 检查输入数组是否为空 - Laravel 5.4
- date - crontab 使用昨天的日期
- perl - 为什么用间接对象调用`system`只会在autodie中给出语法错误
- javascript - 如何获得未选中的单选按钮属性?