如何从python minidom中获取布尔值

时间:2014-11-10 16:12:48

标签: python xml minidom

这让我很难过:

me@here ~
$ python
Python 2.7.8 (default, Oct 20 2014, 09:44:42)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> b=False
>>> b
False
>>> str(b)
'False'
>>> s=str(b)
>>> s
'False'
>>> b=bool(s)
>>> b
True
>>>

那么,如何使用minidom从xml文档中获取布尔值? getAttribute给了我一个字符串,我总是可以这样做:

attr = el.getAttribute( 'bodacious' )
if attr in [ '1', 'true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES' ]:
    return True # a bodacious element
else:
    return False # a most non-bodacious element

但似乎很随意。还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

如果这些都是你迷你裙中可能存在的事情,那么是的。不过,你可以更简洁一点:

attr = el.getAttribute( 'bodacious' ).lower()
return attr in ( '1', 'true', 'y', 'yes' )

甚至内联它:

return el.getAttribute( 'bodacious' ).lower() in ( '1', 'true', 'y', 'yes' )

虽然如果你经常这样做,你会想要提取真值的列表,如:

TRUE_VALS = ( '1', 'true', 'True', 'y', 'yes', 'Y', 'Yes', 'YES' )

然后:

return el.getAttribute( 'bodacious' ) in TRUE_VALS:

答案 1 :(得分:1)

一方面:python如何从对象中获取布尔值

每个python对象都有一个内在的布尔值。一般来说,每个对象都是真实的(即传递给True时它会返回bool),除非它是''None0,{{1}或空容器(如False[])。 (您可以在自己的类中自定义此行为)

这意味着,任何非空字符串都具有真值,导致可能会混淆使用其他语言的人的结果,这些语言具有隐式类型强制,如PHP或JS。但它是一致的,这是您在编程时所需要的:

{}

另一方面:XML作为数据传输语言很糟糕。

您需要跟踪真实或虚假的价值观。假设您想要定义真值,其余的都是假的,您可以执行以下操作:

>>> bool('False')
True
>>> bool('Very false')
True
>>> bool('')
False
>>> bool('0')
True

这可以最大限度地减少您必须处理的特殊情况。它也带来许多风险,例如# Define this in load-time code instead of runtime to avoid redefining it on each call. truthy_values = {'true', '1', ...} ... # Then, in some function, check the value in this way: return attr.lower() in truthy_values 将返回'0'

无论如何,我真正的提示是一劳永逸地放弃XML。如果你使用JSON或YAML,你的生活会更好,更令人满意。