使用lxml
包,按元素文本排序
from lxml import etree
from io import BytesIO
xml_obj = BytesIO(xmlstr)
root = etree.parse(xml_obj).getroot()
# keys list before sorting
print(root.xpath('.//x:Rule/x:Description/text()', namespaces={'x': 'http://www.ProgramConfiguration/2.1'}))
for c in root.xpath('/x:ProgramConfiguration/x:Rules', namespaces={'x': 'http://www.ProgramConfiguration/2.1'}):
c[:] = sorted(c, key=lambda child: (child.xpath('.//x:Description/text()', namespaces={'x': 'http://www.ProgramConfiguration/2.1'})))
# keys list after sorting
print(root.xpath('.//x:Rule/x:Description/text()', namespaces={'x': 'http://www.ProgramConfiguration/2.1'}))
xmlstr = etree.tostring(root, encoding="utf-8", method="xml")
print(xmlstr.decode("utf-8"))
Result:
['Muster, Alex', 'Albert, Peter', 'Rich, Sam', 'Albert, Zack']
['Albert, Peter', 'Albert, Zack', 'Muster, Alex', 'Rich, Sam']
<ProgramConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ProgramConfiguration/2.1">
<Rules>
<Rule RuleId="2" Enabled="true">
<Description>Albert, Peter</Description>
<WatchDirectories>
<WatchDirectory Path="\server201...." WatchSubDirs="false"/>
</WatchDirectories>
<Actions>
</Actions>
</Rule>
<Rule RuleId="4" Enabled="true">
<Description>Albert, Zack</Description>
<WatchDirectories>
<WatchDirectory Path="\server201...." WatchSubDirs="false"/>
</WatchDirectories>
<Actions>
</Actions>
</Rule>
<Rule RuleId="1" Enabled="true">
<Description>Muster, Alex</Description>.
<WatchDirectories>
<WatchDirectory Path="\server201...." WatchSubDirs="false"/>
</WatchDirectories>
<Actions>
</Actions>
</Rule>
<Rule RuleId="3" Enabled="true">
<Description>Rich, Sam</Description>
<WatchDirectories>
<WatchDirectory Path="\server201...." WatchSubDirs="false"/>
</WatchDirectories>
<Actions>