【问题标题】:root.find() not working when called from dictionary- element tree从字典元素树调用时,root.find() 不起作用
【发布时间】: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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多