我试图解析XML文件取决于可能存在或不存在的标签!解析XML文件取决于可能存在或不存在的标签
如何避免这种IndexError而不使用异常处理程序?
python脚本:
#!/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>
,我得到一个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
你为什么不想要使用异常处理程序我认为这是做这件事的好方法。你可以用usr If-else子句来确定一个级别是否存在。但这种方式并不是真正动态的。你可能不知道它有多少级别。 – trantu
因为我有大的XML文件,我认为 - 将需要很长时间来解析,如果有很多异常处理程序PLZ检查[这](http://stackoverflow.com/questions/37022525/loading-data-to-neo4j -from-XML的使用-py2neo) – Zingo