Python: Append two XML tags



I have this XML file and I'd like to read some data out of it using Python's 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>


The result that I wish to have is this :



John Smith
Saint Patrick Thomas


The thing, as you may have noticed, is that sometimes I have 1 GivenName tag and sometimes I have 2 GivenName tags


What I did was this :



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)


It works fine with 1 GivenName tag but not when I have 2.


What can I do?


Thanks!


No comments:

Post a Comment