Parsing blank XML tags with LXML and Python

后端 未结 4 1798
自闭症患者
自闭症患者 2021-01-26 12:58

When parsing XML documents in the format of:


    Blue
    Chevy
    Camaro         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 13:43

    I would catch the exception:

    try:
        print parsedCarData[0]['Model']
    except KeyError:
        print 'No model specified'
    

    Exceptions in Python aren't exceptional in the same sense as in other languages, where they are more strictly linked to error conditions. Instead they are frequently part of the normal usage of modules, by design. An iterator raises StopIteration to signal it has reached the end of the iteration, for example.

    Edit: If you're sure only this item can be empty @CharlesDuffy has it right in that using get() is probably better. But in general I'd consider using exceptions for handling diverse exceptional output easily.

提交回复
热议问题