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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With