首页 > 解决方案 > 在python中解析xml文件时没有得到任何东西

问题描述

我是 python 的初学者,并试图从 xmlfile 解析以下字符串,我可以在其中得到如下输出:

预期输出{macman:(linkedin,facebook,stack overflow)}

这样我就可以找出哪个用户有哪些客户

XML File :  <user name="macman">  <client name="linkedin" /> 
<client name="facebook" />  <client name="stack overflow" /> 
</user>

我正在尝试的代码

import urllib.request as url
import xml.etree.ElementTree as ET

xmlfile=url.urlopen(r'file:///D:/Python/user.html')

tree=ET.parse(xmlfile)

root=tree.getroot()
print(root.tag)

for item in root.findall("./user"):
   users={}
   for child in item:
      users[child.tag]=child.text
   print(users)

标签: pythonxml

解决方案


你需要findall()client不是user. 因此,您的代码应如下所示:

...
users = {root.get("name"): []}
for item in root.findall("client"):
    users[root.get("name")].append(item.get("name"))

print(users)
#{'macman': ['linkedin', 'facebook', 'stack overflow']}

推荐阅读