How can I check attribute existings by Elementtree?
Asked Answered
B

1

14

I need to check certain attributes for existence. Like:

if "blah-blah-blah" is None:
    print "there is no such attribute"
else:
    print "The attribute exists"
Baillargeon answered 21/6, 2012 at 15:25 Comment(4)
Okay "blah-blah-blah" makes no sense... The syntax isn't even Python and I can't see any relation to Elementtree - please clarify thisAnastice
@Jon Why is the syntax not Python? Except for "blah-blah-blah" which is not a valid name. Edit: right, the missing colon after else...Engaged
Do you have to verify if there is certain attribute in some specific element, or whether the attribute is set in any element? Could you post an example of what you are trying to do? An example of the input XML doc? Also, an example of the expected output?Emphasis
And not sure I should bother mentioning, whatever == None, should be written whatever is NoneAnastice
E
36

Element objects have all the attributes in the attrib dict.

if 'blah' not in elem.attrib:
   print "there is no such attribute"
Engaged answered 21/6, 2012 at 15:30 Comment(2)
Where can i set the tag? What is 'blah'? blah == attrib?Baillargeon
@Baillargeon I gave the best answer I was able to given how you stated the question. How to set the tag is a different question, and the answer will depend on what you need to do with the XML document. I suggest reading the documentation I link to and also a short guide on how to ask.Engaged

© 2022 - 2024 — McMap. All rights reserved.