python-3.xxmlelementsax

Reading an optional attribute of a XML Node in python3


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


Solution

  • tagName doesn't "have" anything, it's just a string. The in operator checks for a substring number inside the name of the tag. 'number' in 'somenumberthing' evaluates to true. Clearly not what you want here.

    The attr has the actual values; the condition you are looking for is rather: "if the attributes has a value for the key 'number'", e.g:

    self.priority = attrs['number'] if 'number' in attrs else '0'
    

    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 get method with the default value:

    self.priority = attrs.get('number', default='0')