parsing XML file depends on tags which may or may not be existed
Question: Im trying to parse an XML file depends on a tag which may or may not be
existed !

how I can avoid this IndexError without using exception handler ?

python script:

    
    
    #!/usr/bin/python3
    from xml.dom import minidom
    
    
    doc = minidom.parse("Data.xml")
    
    persons = doc.getElementsByTagName("person")
    
    for person in persons:
        print(person.getElementsByTagName("phone")[0].firstChild.data)
    

Data.xml :

    
    
    <?xml version="1.0" encoding="UTF-8"?>
    <obo>
        <Persons>
            <person>
                <id>XA123</id>
                <first_name>Adam</first_name>
                <last_name>John</last_name>
                <phone>01-12322222</phone>
            </person>
            <person>
                <id>XA7777</id>
                <first_name>Anna</first_name>
                <last_name>Watson</last_name>
                <relationship>
                    <type>Friends</type>
                    <to>XA123</to>
                </relationship>
                <!--<phone>01-12322222</phone>-->
            </person>
        </Persons>
    </obo>
    

and I get an IndexError:

    
    
    01-12322222
    Traceback (most recent call last):
      File "XML->Neo4j-try.py", line 29, in <module>
        print(person.getElementsByTagName("phone")[0].firstChild.data)
    IndexError: list index out of range
    


Answer: First, you need to check whether current person has phone data, and proceed
further only if it has. Also, it is slightly better to store the result of
`getElementsByTagName()` in a variable to avoid doing the same query
repeatedly, especially when the actual XML has a lot more content in each
`person` element :

    
    
    for person in persons:
        phones = person.getElementsByTagName("phone")
        if phones:
            print(phones[0].firstChild.data)
    

