Tell me what could be the problem:

The following xml file is given:

<?xml version="1.0" encoding="UTF-8"?> <СообщОтказ_115ФЗ> <СлужЧасть> <ВерсияФормата>1.2</ВерсияФормата> <ДатаСообщения>10/12/2018</ДатаСообщения> <ТелОператор>8(499) 237-33-32</ТелОператор> <ЭлектроннаяПочта>svc_550P@cbr.ru</ЭлектроннаяПочта> </СлужЧасть> <ИнформЧасть> <СведФЛИП> <ФИОФЛИП> <Фам>Массссссс</Фам> <Имя>Насссссс</Имя> <Отч>Дсссссссс</Отч> </ФИОФЛИП> <ИННФЛИП></ИННФЛИП> <СведДокУдЛичн> <ВидДокКод>21</ВидДокКод> <ВидДокНаименование>Паспорт гражданина Российской Федерации (для гражданина Российской Федерации, достигшего 14 лет)</ВидДокНаименование> <СерияДок>8888</СерияДок> <НомДок>7777777</НомДок> <ДатВыдачиДок>01/10/2000</ДатВыдачиДок> <КемВыданДок>Мухоршибирский РОВД республики Бурятия</КемВыданДок> <КодПодр>032-016</КодПодр> </СведДокУдЛичн> <ДатаРождения>10/00/1900</ДатаРождения> <МестоРожд> <КодОКСМ>643</КодОКСМ> <СтранаНаименование>РОССИЙСКАЯ ФЕДЕРАЦИЯ</СтранаНаименование> <КодСубъектаПоОКАТО>81</КодСубъектаПоОКАТО> <Район>МУХОРШИБИРСКИЙ Р-Н</Район> <Пункт>ЦОЛГА С</Пункт> </МестоРожд> <КодОКСМ>643</КодОКСМ> <СтранаНаименование>РОССИЙСКАЯ ФЕДЕРАЦИЯ</СтранаНаименование> <ПризнакПубЛицо>0</ПризнакПубЛицо> </СведФЛИП> </Участник> </Раздел2> 

Trying to parse with the following code:

 from xml.dom import minidom with open("cbr_fio.xml", 'rb') as f: doc = minidom.parse(f) root = doc.getElementsByTagName("СведФЛИП") result = [] name = {} for el in root: if el.getElementsByTagName('ФИОФЛИП'): name['FIO'] = f"{el.getAttribute('Фам')} {el.getAttribute('Имя')} {el.getAttribute('Отч')}" for data in root: if el.getElementsByTagName('СведДокУдЛичн'): name['PassType'] = el.getAttribute('ВидДокНаименование') name['PassNumber'] = f"{el.getAttribute('СерияДок')} {el.getAttribute('НомДок')}" result.append(name) print(result) 

But in the end gives empty values

 [{'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, {'FIO': ' ', 'PassType': '', 'PassNumber': ' '}, 

    2 answers 2

    If the example xml put all the closing tags

     import xmltodict with open("cbr_fio.xml", 'rb') as f: o_dict = xmltodict.parse(f.read()) import json print(json.dumps(o_dict , indent=2, ensure_ascii=False)) 

    out

     { "СообщОтказ_115ФЗ": { "СлужЧасть": { "ВерсияФормата": "1.2", "ДатаСообщения": "10/12/2018", "ТелОператор": "8(499) 237-33-32", "ЭлектроннаяПочта": "svc_550P@cbr.ru" }, "ИнформЧасть": { "Раздел2": { "Участник": { "СведФЛИП": { "ФИОФЛИП": { "Фам": "Массссссс", "Имя": "Насссссс", "Отч": "Дсссссссс" }, "ИННФЛИП": null, "СведДокУдЛичн": { "ВидДокКод": "21", "ВидДокНаименование": "Паспорт гражданина Российской Федерации (для гражданина Российской Федерации, достигшего 14 лет)", "СерияДок": "8888", "НомДок": "7777777", "ДатВыдачиДок": "01/10/2000", "КемВыданДок": "Мухоршибирский РОВД республики Бурятия", "КодПодр": "032-016" }, "ДатаРождения": "10/00/1900", "МестоРожд": { "КодОКСМ": "643", "СтранаНаименование": "РОССИЙСКАЯ ФЕДЕРАЦИЯ", "КодСубъектаПоОКАТО": "81", "Район": "МУХОРШИБИРСКИЙ Р-Н", "Пункт": "ЦОЛГА С" }, "КодОКСМ": "643", "СтранаНаименование": "РОССИЙСКАЯ ФЕДЕРАЦИЯ", "ПризнакПубЛицо": "0" } } } } } } 

      Фам , Имя and Отч are not attributes of the ФИОФЛИП tag, but child tags. Try this

       def first(items): try: return items[0] except (IndexError, TypeError): return None def get_text(node): return ''.join(n.data for n in get getattr(node, 'childNodes', []) if n.nodeType == n.TEXT_NODE) def get_child_text(parent, name): return get_text(first(parent.getElementsByTagName(name))) name['FIO'] = ' '.join(get_child_text(el, i) for i in ['Фам', 'Имя', 'Отч']) 
      • Unfortunately, the problem did not resolve either an error out of range or a DOM Element: Fam at at 0x7f41ad83a9c8> :( - Pavel
      • on the corrected code, it gives a TypeError error: sequence item 0: expected str instance, Element found - Pavel
      • Check out the new version. Added a check for the presence of a child element and a function to extract text from a tag. - Sergey Gornostaev
      • Alas: (((Traceback (most recent call last): File "cbr_xml.py", line 32, in <module> name ['FIO'] = '' .join (get_child_text (el, i) for i in [' Fam, Name, Report]] File "cbr_xml.py", line 32, in <genexpr> name ['FIO'] = '' .join (get_child_text (el, i) for i in ['Fam ',' Name ',' Report ']) File "cbr_xml.py", line 26, in get_child_text return get_text (first (parent.getElementsByTagName (name))) File "cbr_xml.py", line 23, in get_text return' '.join (n.data for n in nodes or [] if n.nodeType == n.TEXT_NODE) ​​TypeError:' Element 'object is not iterable - Pavel
      • Corrected. Check it out. - Sergey Gornostaev