T
T
Ti-Jey2020-06-10 19:32:38
Python
Ti-Jey, 2020-06-10 19:32:38

How to "parse" data from an XML file, sort it in a certain way and display it in Excel?

I'm a beginner, so I'm writing a crooked code ....
The question is how to parse data from an XML file, sort it by name and display it in Excel:

<?xml version="1.0" encoding="UTF-8"?>
<NewDataSet>
<Persons>
  <Member>
    <ID>5942</ID>
    <Name>Григорьев Гордий</Name>
    <Age>29</Age>
  </Member>
  <Member>
    <ID>8559</ID>
    <Name>Яковлев Григорий</Name>
    <Age>58</Age>
  </Member>
  <Member>
    <ID>14543</ID>
    <Name>Доронин Евгений</Name>
    <Age>53</Age>
  </Member>
  <Member>
    <ID>15470</ID>
    <Name>Родионов Митрофан</Name>
    <Age>33</Age>
  </Member>
  <Member>
    <ID>17662</ID>
    <Name>Николаев Эдуард</Name>
    <Age>22</Age>
  </Member>
  <Member>
    <ID>27164</ID>
    <Name>Суворов Август</Name>
    <Age>31</Age>
  </Member>


Here is my code, but sorting is by Last Name, it is necessary by First Name:
import xml.etree.ElementTree as ET
import copy
a = {}
b = []
def getName(XML_path):
    tree = ET.parse(XML_path)
    root = tree.getroot()
    for y in root[0]:
        for i in range(3):
            a.update({y[i].tag : y[i].text})
        x = copy.deepcopy(a) #make deep copy (a)
        b.append(x)
    global s
    s= sorted(b, key=lambda x: x['Name'])
    return print(s)

XML_path = "small_data.xml"

getName(XML_path)

import xlsxwriter
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet("sheet1")

row = 0
col = 0
for key in s[0]:
    worksheet.write(row, col, key)
    col+=1
for x in s:
    col = 0
    row += 1
    for item in x.values():
        worksheet.write(row, col, item)
        col += 1
workbook.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-06-10
@Ti-Jey

javedimka 's answer :
s = sorted(b, key=lambda x: x['Name'].split()[1])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question