Я пытаюсь проанализировать XML-файл с несколькими тегами внутри корневого тега. Я могу получить значения, но текст из первого тега перезаписывается текстом из второго тега.
Мой XML-файл:
<?xml version="1.0" encoding="UTF-8"?>
<Artists>
<Title>
<id>1</id>
<titlenumber>119103839</titlenumber>
<performed>N</performed>
</Title>
<Title>
<id>2</id>
<titlenumber>11938837</titlenumber>
<notes>Second Album</notes>
<performed>N</performed>
</Title>
</Artists>
Я попытался создать словарь, в которомЯ могу хранить значения для каждого тега.
Код:
def parse(self,xml_content):
contents = fromstring(xml_content)
info = {}
for elem in contents:
if elem.tag == 'Artists':
art_id, art_title, art_notes, art_perform = self.get_artist_details(elem)
info['art_id'] = art_id
info['art_title'] = art_title
info['art_notes'] = art_notes
info['art_perform'] = art_perform
return info
def get_artist_details(self, elem_content):
found = False
art_id, art_title, art_notes, art_perform = '','','','',''
for child in elem_content:
if child.tag == 'Title':
found = True
for sub in child:
if sub.tag == 'id':
art_id = sub.text
if sub.tag == 'titlenumber':
art_title = sub.text
if sub.tag == 'notes':
art_notes = sub.text
if sub.tag == 'performed':
art_perform = sub.text
if found is True:
return art_id, art_title, art_notes, art_perform
else:
return '','','',''
Вывод:
{art_id:'2', art_title:'11938837', art_notes:'Second Album', art_perform: 'N'}
Ожидаемый вывод:
{art_id:'1', art_title:'119103839', art_notes:'', art_perform: 'N'}
{art_id:'2', art_title:'11938837', art_notes:'Second Album', art_perform: 'N'}
Iхотите, чтобы в выводе было 2 строки с текстом, совпадающим для каждого тега в любом типе данных. Есть ли способ сделать это без использования find или findall? Спасибо.