I'm trying to read a XML file in SAX in Python3, because in my pet project I have in inptu a full directory of XML file representing some GTD projects1 .
The file has this format
<project name = "name of project">
<action number="2" > action to do</action>
</project>
my SAX parsing is in the class MyHandler and my problem is that I have defined the attribute "number" as optional, but it's not working.
In the instruction
def startElement(self, tagName, attrs):
#etc
elif tag_name.isAction():
self.priority = attrs['number'] if 'number' in tagName else '0'
I verify if the current tag is an Action tag: if yes, I populate the self.priority attribute of the class reading the XML attribute "number" if exists, otherwise I put '0'.
My problem is
attrs['number'] if 'number' in tagName
that is false in every case
How I can verify, in startElement method, if the tagName has an attribute 'number'?
In stackoverflow I found sonly examples with Stax
Thank you
tagNamedoesn't "have" anything, it's just a string. Theinoperator checks for a substringnumberinside the name of the tag.'number' in 'somenumberthing'evaluates to true. Clearly not what you want here.The
attrhas the actual values; the condition you are looking for is rather: "if the attributes has a value for the key 'number'", e.g:This is a very common pattern for dict like objects, and I assume this is what SAX gives you so I would recommend using the
getmethod with the default value: