Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an attribute exists in some XML

Tags:

python

xml

lxml

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.

like image 489
Jay Avatar asked Apr 11 '12 23:04

Jay


1 Answers

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...
like image 140
Charles Duffy Avatar answered Oct 18 '22 19:10

Charles Duffy