首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中的XML解析(xml.etree.ElementTree)

python中的XML解析(xml.etree.ElementTree)
EN

Stack Overflow用户
提问于 2020-01-28 05:42:25
回答 1查看 2.3K关注 0票数 1

我使用导入xml.etree.ElementTree作为ET来解析python中的xml文件。

我试过:

代码语言:javascript
复制
   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:

代码语言:javascript
复制
<data>
    <database>
        <name>qwe</name>
        <username>postgres</username>
        <password>1234</password>
        <host>localhost</host>
        <port>5432</port>
    </database>
</data>

但是我想要XML文件,比如:

代码语言:javascript
复制
<data>
<database name="abc"  username="xyz" password="dummy" host="localhost" port="5432"/>
</data>

如果我喜欢这个,root.text不是working.Can --有人告诉我如何访问它吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-28 06:02:19

试试下面的代码,

代码语言:javascript
复制
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']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59942751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档