Sorting XML in python etree

后端 未结 2 1516
野性不改
野性不改 2020-12-10 14:46

I know this question has been asked before but I am struggling to get it to work with my example and would really appreciate some help. What I am trying to achieve seems fai

2条回答
  •  生来不讨喜
    2020-12-10 15:24

    Using ElementTree you can do this:

    import xml.etree.ElementTree as ET
    
    def sortchildrenby(parent, attr):
        parent[:] = sorted(parent, key=lambda child: child.get(attr))
    
    tree = ET.parse('input.xml')
    root = tree.getroot()
    
    sortchildrenby(root, 'NAME')
    for child in root:
        sortchildrenby(child, 'NAME')
    
    tree.write('output.xml')
    

提交回复
热议问题