root.find() 从字典元素树调用时不起作用

root.find() not working when called from dictionary- element tree

我目前正在使用模块元素树和 urllib 来 access/parse 和 return 来自 xml 个文件的值。

使用 root.find/root.findall() 方法和 XPath 语法在 xml 中找到所需的信息。然后使用 (.text) 将 return 的值设为 child/grandchild 元素。

当将每个 root.find() 分配给一个变量然后获取变量并附加 (.text) 时,我能够毫无问题地解析和 return 值。

(即)

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'

所以这可能是我忽略的一个简单问题,但这两种方法 return 是否具有相同的值?元素树模块可以从字典中读取root.find()吗?

您正在将字典值设置为文字字符串。也就是这个:

'Cam': "root.find('./Cameras/Camera/Connected')",

正在将键 Cam 的值设置为字符串值 root.find('./Cameras/Camera/Connected')。您想要实际调用该函数并将键设置为 return 值,因此您需要删除引号:

'Cam': root.find('./Cameras/Camera/Connected'),