Q:

Better way to throw exception with lxml findtext when find nothing

I use lxml etree to parse a xml file and want to make sure some fields are there in the file. My code would be like this.
try:
    with open(filename, 'r') as conf:
        rt = etree.parse(conf)   

    CONF['user1'] = rt.findtext('//user1')
    if not CONF['user1']:
        raise ValueError('Cannot find uer1 in conf file')  

    CONF['field2'] = rt.findtext('//field2') 
    if not CONF['field2']:
        #raise again 

    # And so on         
Except Exception as err:
    print err

You can see the coding is tedious. Are there something like rt.findtext('//field', default=rasie exception("With my message"))?

A:

I do not see any such methods to directly do this , but you can create your own function to do this , Example -
def findtext_with_exception(element,xpath,message):
    ret = element.findtext(xpath)
    if not ret:
        raise ValueError(message)
    return ret

Then you can use this method instead of findtext as -
CONF['user1'] = findtext_with_exception(rt, '//user1', 'Cannot find uer1 in conf file')
CONF['field2'] = findtext_with_exception(rt, '//field2', '<Next message>')

