【问题标题】:etree get attribute as a value instead of a stringetree 获取属性作为值而不是字符串
【发布时间】:2011-06-21 09:07:46
【问题描述】:

对于给定的元素,我想检查 xsi:nil 属性是否设置为 true。

我当前的代码是

xsinil = dataFact.get('{http://www.w3.org/2001/XMLSchema-instance}nil', False)

但不是True xsinil 是字符串类型...

最好的解决方案是什么?我不认为这很优雅:

xsinil=dataFact.get('{http://www.w3.org/2001/XMLSchema-instance}nil', False)
if xsinil == 'true' or xsinil == '1' :
    xsinil = True

【问题讨论】:

    标签: python lxml elementtree


    【解决方案1】:

    这看起来更好:

    xsinil = dataFact.get('...', False) in ('true', '1')
    

    仅当get 函数的结果是True'true''1' 之一时,它才会将True 分配给xsinil 变量。

    【讨论】:

    • -1 Element.get(attribute_name, False) 永远不会返回 True
    • 同意,最终答案将是xsinil = dataFact.get('......') in ('true', '1')
    【解决方案2】:

    Element.get() 的第二个参数几乎无关紧要——只是不要使用True

    您只需要:

    xsinil = dataFact.get('......') in ('true', '1')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多