Home > other >  Handle no element return
Handle no element return

Time:11-04

I have 3 documents xsd, one with minVersion = 1.1, second with minVersion = 1.0 and another one without minVersion element. I get element data from first two, but third one does not return anything, not even "None". How to handle this?

My code:

import lxml.etree as ET
dom = ET.parse(u'cbs.xsd')
rootxml = dom.getroot()
nss = rootxml.nsmap
for subtag in rootxml.xpath(u'//@vc:minVersion', namespaces=nss):
    print(subtag)
    if subtag == '1.1':
        print('Found! 1.1 version')
    elif subtag == '1.0':
        print('Found! 1.0 version')
    else:
        print('not found')

As I said above, I expect that when vc:minVersion is not found, it would return even something.

CodePudding user response:

Your for loop isn't being entered because rootxml.xpath isn't finding anything. Try this:

import lxml.etree as ET
dom = ET.parse(u'cbs.xsd')
rootxml = dom.getroot()
nss = rootxml.nsmap
for subtag in rootxml.xpath(u'//@vc:minVersion', namespaces=nss):
    print(f'Found! {subtag} version')
    break
else:
    print('not found')
  • Related