How to test if an attribute exists in some XML
lxml, python, xml
Solution
I'm surprised that a test for null values on an attribute which often won't exist works ever -- what you should be doing is checking whether it exists, not whether it's empty:
if 'Reference' in current_element.attrib:
...do something with it...
Problem
I have some XML that I am parsing in python via lxml. I am encountering situations where some elements have attributes and some don't. I need to extract them if they exist, but skip them if they don't - I'm currently landing with errors (as my approach is wrong...) I have deployed a testfornull, but that doesn't work in all cases: Code: ``` if root[0][a][b].attrib == '<>': ByteSeqReference = "NULL" else: ByteSeqReference = (attributes["Reference"]) ``` XML A: ``` <ByteSequence Reference="BOFoffset"> ``` XML B: ``` <ByteSequence Endianness = "little-endian" Reference="BOFoffset"> ``` XML C: ``` <ByteSequence Endianness = "little-endian"> ``` XML D: ``` <ByteSequence> ``` My current method can only deal with A, B or D. It can not cope with C.