python - 在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)
解决方案
你需要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']}
推荐阅读
- python - 使用分类特征的协同过滤
- c# - ScrollViewer 拇指没有移动
- visual-studio-code - VS Code -- 注释 .jsx 语法
- arrays - 在 C# 中初始化一个结构数组
- java - java生成并行IntStream(和其他流)问题
- highcharts - HighCarts 饼图未在饼图标签中显示值
- c# - 在表单之间传递数据以绘制表面,不起作用
- xpath - 在 current-group() 上使用 XPath
- jquery - 大尺寸的 svg 无法正常工作 如何在 react-pan-zoon-svg 中设置大 svg?
- bash - 同时出现两个“if”条件