Reputation: 377
For the following XML file, I'm trying to get all the book titles and append it to a list.
XML file-
<?xml version="1.0" encoding="UTF-8"?>
<Text>
<Library>
<Book>
<Title>XYZ</Title>
</Book>
<Book>
<Title>ABC</Title>
</Book>
</Library>
</Text>
I'm using ElementTree to extract the tag values using this code-
for child in root.iter('Text'):
t1=(child.find('Library/Book/Title').text)
t2=(child.find('Library/Book/Title').text)
print (t1,t2)
I'm unable to get the second tag value. Is it possible to get both the values in one find and append it to a list?
Upvotes: 1
Views: 65
Reputation: 38
You can get both values in a list using findall instead of find
Updated the code so it suits the comment:
library = []
for text in root.findall('Library'):
titles = [title.text for title in text.findall('Book/Title')]
library.append(titles)
This will make an array per library and adds each book title to that array Result:
>>>print(library)
[['XYZ','ABC'],['LMN','PQR']]
here is the documentation
Upvotes: 1