我有这个XML文件,我想使用Python的xml.etree从其中读取一些数据:
<a>
<b>
<AuthorName>
<GivenName>John</GivenName>
<FamilyName>Smith</FamilyName>
</AuthorName>
<AuthorName>
<GivenName>Saint</GivenName>
<GivenName>Patrick</GivenName>
<FamilyName>Thomas</FamilyName>
</AuthorName>
</b>
</a>
我希望得到的结果是:
John Smith
Saint Patrick Thomas
您可能已经注意到,问题是有时我有1个GivenName标签,有时我有2个GivenName标签
我所做的是:
from xml.etree import ElementTree as ET
xx = ET.parse('file.xml')
authorName = xx.findall('.//AuthorName')
for name in authorName:
print(name[0].text + " " + name[1].text)
它可以使用1个GivenName标记正常工作,但是当我有2个时则不能。
我能做什么?
谢谢!
最佳答案
尝试这个:
from xml.etree import ElementTree as ET
xx = ET.parse('file.xml')
authorName = xx.findall('.//AuthorName')
for name in authorName:
nameStr = ' '.join([child.text for child in name])
print(nameStr)
您必须查看authorName内的所有子标记,获取它们的文本,然后将它们加入到您的nameStr中。