How to check if an attribute exists in some XML files

I have XML that I am processing in python through lxml.

I come across situations where some elements have attributes and some do not.

I need to extract them if they exist, but skip them if they do not - I am coming up with errors now (since my approach is wrong ...)

I deployed testfornull, but this does not work in all cases:

the 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 work with A, B, or D. It cannot handle C.

+8
python xml lxml
source share
1 answer

I am surprised that a null test for an attribute that often will not exist never works - what you should do is check if it exists and not if it is empty:

 if 'Reference' in current_element.attrib: ...do something with it... 
+17
source share

All Articles