خرید بک لینک

Vote count: 0

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>Aa</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

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 16 ارديبهشت 1395 ساعت: 13:08

صفحه بندی