我有許多帶有子名稱的'root'標籤。我想對「根」塊進行排序,按「名稱」元素按字母順序排列。已嘗試過lxml/etree/minidom但無法正常工作... 我無法解析標籤中的值,然後對父根標籤進行排序。按子元素對XML標籤進行排序Python
<?xml version='1.0' encoding='UTF-8'?>
<roots>
<root>
<path>//1.1.1.100/Alex</path>
<name>Alex Space</name>
</root>
<root>
<path>//1.1.1.101/Steve</path>
<name>Steve Space</name>
</root>
<root>
<path>//1.1.1.150/Bethany</path>
<name>Bethanys</name>
</root>
</roots>
這是我曾嘗試:
import xml.etree.ElementTree as ET
def sortchildrenby(parent, child):
parent[:] = sorted(parent, key=lambda child: child)
tree = ET.parse('data.xml')
root = tree.getroot()
sortchildrenby(root, 'name')
for child in root:
sortchildrenby(child, 'name')
tree.write('output.xml')
所以你想要名字先來? –