E
E
Elbek M2019-11-13 17:26:52
Python
Elbek M, 2019-11-13 17:26:52

How to sort xml in python?

I have an xml file with the following structure:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <objects>
        <object name="D2">
            <value>a</value>
        </object>
        <object name="D1">
            <value>b</value>
        </object>
        <object name="M1">
            <value>1</value>
        </object>
        <object name="M3">
            <value>3</value>
        </object>
        <object name="M2">
            <value>2</value>
        </object>
    </objects>
</root>

I need to sort them by the name tag, so that in the end it turns out: D1 D2 M1 M2 M3, and after that pull out the values ​​corresponding to the tags, that is, the result should be an array ['b', 'a', '1', '2' , '3'].
Working with xml for the first time, here is what I was able to do:
import xml.etree.ElementTree as ET
 
value = []
root = ET.parse('xml_data.xml').getroot()
 
for type_tag in root.findall('objects/object/value'):
    value.append(type_tag.text)

Here in value is not sorted data.
I would appreciate your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Elvis, 2019-11-13
@Elbek_M

Remove unnecessary prints, they are just for clarity

import xml.etree.ElementTree as ET
import collections
 
value = {}
root = ET.parse('xml_data.xml').getroot()
 
for type_tag in root.findall('objects/object'):
    value[type_tag.attrib['name']] = type_tag.find('value').text

print(value)
sortedvalue = collections.OrderedDict(sorted(value.items()))
print(sortedvalue)
sortedvaluelist = []
for k, v in sortedvalue.items():
    sortedvaluelist.append(v)
print(sortedvaluelist)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question