1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to create a list of list using findall option? I want to create something like [[XYZ,ABC],[LMN,PQR]] but at the moment all values are placed in a 1D list as [XYZ,ABC,LMN,PQR].
The data per Text block?
Data per Library block.
Edited the code for you so it matches how you want it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.