[英]XML Parsing in python(xml.etree.ElementTree)
我使用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>
如果我这样做,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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.