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

2024-03-28 09:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用import xml.etree.ElementTree作为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>

如果我这样做,根目录[0][0]。文本无效。有人能告诉我如何访问它吗


Tags: 文件textnameimporthostdataportusername
1条回答
网友
1楼 · 发布于 2024-03-28 09:30:52

试试下面的代码

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']

相关问题 更多 >