如何通过ElementTree检查属性是否存在?

14
我需要检查某些属性是否存在,比如:
if "blah-blah-blah" is None:
    print "there is no such attribute"
else:
    print "The attribute exists"

好的,“blah-blah-blah” 毫无意义... 语法甚至不是 Python,我也看不出任何与 Elementtree 相关的东西 - 请澄清一下。 - Jon Clements
@Jon 为什么语法不是Python?除了“blah-blah-blah”这个无效的名称。编辑:对了,在else后面缺少冒号... - Lev Levitsky
你需要验证某个特定元素中是否存在某个属性,或者该属性是否在_任何_元素中设置吗?你能否提供一个你正在尝试做的示例?一个输入XML文档的示例?还有一个期望输出的示例? - brandizzi
不确定是否值得一提,whatever == None 应该写成 whatever is None - Jon Clements
1个回答

36

Element对象包含在attrib字典中的所有属性。

if 'blah' not in elem.attrib:
   print "there is no such attribute"

我在哪里可以设置标签? 什么是“blah”?blah == 属性吗? - user1464922
1
@user1464922 根据你提出的问题,我已经给出了我能够提供的最佳答案。如何设置标签是一个不同的问题,答案将取决于您需要对XML文档做什么。我建议阅读我提供的文档,并查看有关如何提问的简短指南。 - Lev Levitsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接