我有这样的XML:
<?xml version="1.0"?>
<Server>
<name>johny</name>
<address>statestreet</address>
<city>Hyderabad</city>
</Server>
我需要将每个属性存储在代码中的单独变量中。所以我正在编写像这样的代码
import xml.etree.ElementTree as et
tree=et.parse('sample.xml')
root=tree.getroot()
for i in root.findall('Server'):
name=i.find('name').text
address = i.find('address').text
city = i.find('city').text
但它没有存储任何东西。请帮助我
答案 0 :(得分:0)
我得到了一个解决方案。我写了一个函数:
def xmldata():
config_xml = et.parse('sample.xml')
root = sample.getroot()
for child in root.getchildren():
if child.tag=='name':
name =child.text
if child.tag=='address':
address =child.text
if child.tag=='city':
city =child.text
return name,address,city
但是当我在main函数中调用def时,它以list ('johny','statestreet','hyderabad')
的形式出现。如何以字典(name:'johny',address:'statestreet',city:'hyderabad')
答案 1 :(得分:0)
这个怎么样:
def xmldata():
config_xml = et.parse('sample.xml')
root = sample.getroot()
result = {}
for child in root.getchildren():
if child.tag=='name':
result['name'] =child.text
if child.tag=='address':
result['address'] =child.text
if child.tag=='city':
result['city'] =child.text
return result
你会得到:{'name':'johny','address':'statestreet','city':'hyderabad'}
返回