示例 XML 文档
<Authors>
<Author>
<LastName>def</LastName>
<age>20</age>
</Author>
<Author>
<ForeName>ghi</ForeName>
<age>22</age>
</Author>
<Author>
<ForeName>mno</ForeName>
<LastName>pqr</LastName>
<age>23</age>
</Author>
</Authors>
样本输出
Author:
FirstName : -
LastName : def
Author:
FirstName : ghi
LastName : -
Author:
FirstName : mno
LastName : pqr
示例代码
import xml.dom.minidom
# use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("sampleinput.xml");
auth = doc.getElementsByTagName('Author')
for a in auth:
print("Author:")
try:
print("FirstName : ",a.getElementsByTagName("ForeName")[0].firstChild.data)
except:
print("FirstName : - ")
try:
print("LastName : ",a.getElementsByTagName("LastName")[0].firstChild.data)
except:
print("LastName : - ")
如果找不到相应的标签,我想插入一个“-”符号。有没有其他可靠的方法可以做到这一点而不是尝试和排除?
动漫人物
相关分类