18

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.

Jay
  • 753
  • 3
  • 11
  • 19

1 Answers1

35

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...
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Ahhh. thats how it works. (I was surprised too.... ). Thanks for your time, I appreciate it. That completely fixes it. – Jay Apr 11 '12 at 23:32