使用python-etree中的值对XML进行排序



下面是我试图使用etree对fullName中的值进行排序的xml考虑按字母顺序对进行排序

<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
<labels>
<fullName>AnAutoQuote</fullName>
<value>This is an automatically generated quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Automatic Quote</shortDescription>
</labels>
<labels>
<fullName>AManualQuote</fullName>
<value>This is a manual quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Manual Quote</shortDescription>
</labels>
</CustomLabels>

我尝试过的代码,但它返回的xml与输入中的xml相同。这里xml包含为输入和解析器读取的文件是编码设置为utf-8的xml解析器


root = objectify.string(xml, parse)
for r in root.iter("labels"):
r[:] = sorted(r, key = lambda ch: -(ch.tag=="fullname"))
print(etree.toStrin(root).decode("utf-8))
root = objectify.fromstring(xml)
root.labels = sorted(root.labels, key=lambda tag: tag.fullName)

完整代码示例:

from lxml import objectify, etree
xml = '''<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
<labels>
<fullName>ZZZAManualQuote</fullName>
<value>This is a manual quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Manual Quote</shortDescription>
</labels>
<labels>
<fullName>AnAutoQuote</fullName>
<value>This is an automatically generated quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Automatic Quote</shortDescription>
</labels>
<labels>
<fullName>AManualQuote</fullName>
<value>This is a manual quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Manual Quote</shortDescription>
</labels>
</CustomLabels>'''
root = objectify.fromstring(xml)
root.labels = sorted(root.labels, key=lambda tag: tag.fullName)
print(etree.tostring(root, pretty_print=True).decode('utf-8'))

输出

<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
<labels>
<fullName>AManualQuote</fullName>
<value>This is a manual quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Manual Quote</shortDescription>
</labels>
<labels>
<fullName>AnAutoQuote</fullName>
<value>This is an automatically generated quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Automatic Quote</shortDescription>
</labels>
<labels>
<fullName>ZZZAManualQuote</fullName>
<value>This is a manual quote.</value>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Manual Quote</shortDescription>
</labels>
</CustomLabels>

最新更新