【发布时间】:2020-09-22 19:37:46
【问题描述】:
我目前正在使用模块元素树和 urllib 来访问/解析和返回 xml 文件中的值。
使用 root.find/root.findall() 方法和 XPath 语法在 xml 中定位所需的信息。然后使用 (.text) 返回子/孙元素的值。
当将每个 root.find() 分配给一个变量然后获取该变量并附加 (.text) 时,我能够毫无问题地解析并返回该值。
(即)
x= root.find(./Cameras/Camera/Connected')
print (x.text)
==> True
但是,我想将这些“root.find()”放在字典中,稍后在脚本中调用它们。
(即)
location= {
'Cam': "root.find('./Cameras/Camera/Connected')",
'Mic': "root.findall('./Audio/Input/Connectors/Microphone')",
'Prod_ID': "root.find('./SystemUnit/ProductPlatform')"
}
但是,当按键索引到字典然后尝试添加 (.text) 时,我收到以下错误;
y=location['Cam']
print (y.text)
==> AttributeError: 'str' object has no attribute 'text'
所以这可能是我忽略的一个简单问题,但这两种方法返回相同的值吗?元素树模块可以从字典中读取 root.find() 吗?
【问题讨论】:
-
您的预期输出是什么?如果你只是
print(y)呢? -
这将使我返回我的密钥
Cam的值我的预期输出是运行该值root.find('./Cameras/Camera/Connected')并解析 xml 以在 xml 中返回这个特定值所以我这个实例会从文件中返回True。
标签: python dictionary xml-parsing urllib elementtree