Answer the question
In order to leave comments, you need to log in
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>
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question