简体   繁体   English

排序 xml 节点

[英]Sorting xml nodes

Let's say I have the following xml:假设我有以下 xml:

  <editions>
    <edition language="English">en.wiktionary.org</edition>
    <edition language="French">fr.wiktionary.org</edition>
    <edition language="Vietnamese">vi.wiktionary.org</edition>
    <edition language="Turkish">tr.wiktionary.org</edition>
    <edition language="Spanish">es.wiktionary.org</edition>
  </editions>

I can grab all 'editions' in Xpath using:我可以使用以下方法获取 Xpath 中的所有“版本”:

//editions/edition

This can be tested here: https://www.freeformatter.com/xpath-tester.html .这可以在这里测试: https://www.freeformatter.com/xpath-tester.html Does XPath support a way to sort results? XPath 是否支持对结果进行排序的方法? For example, I would like to sort descendingly by the language attribute, so the correct 'answer' would be:例如,我想按语言属性降序排序,所以正确的“答案”是:

Element='<edition language="Vietnamese">vi.wiktionary.org</edition>'
Element='<edition language="Turkish">tr.wiktionary.org</edition>'
Element='<edition language="French">fr.wiktionary.org</edition>'
Element='<edition language="Spanish">es.wiktionary.org</edition>'
Element='<edition language="English">en.wiktionary.org</edition>'

Note I have tagged this question with python, but any language can be used here.注意我已经用 python 标记了这个问题,但这里可以使用任何语言。 In python I would do it outside XPath (because I don't know how) doing something like:在 python 我会在 XPath 外面做(因为我不知道怎么做)做类似的事情:

nodes = sorted(etree.fromstring(s).xpath('//edition'), 
    key=lambda node: node.attrib['language'], reverse=True)
nodes[0].text
# 'vi.wiktionary.org'

Try the below试试下面

import xml.etree.ElementTree as ET

xml = ''' <editions>
    <edition language="English">en.wiktionary.org</edition>
    <edition language="French">fr.wiktionary.org</edition>
    <edition language="Vietnamese">vi.wiktionary.org</edition>
    <edition language="Turkish">tr.wiktionary.org</edition>
    <edition language="Zoo">zz.wiktionary.org</edition>
    <edition language="Spanish">es.wiktionary.org</edition>
  </editions>'''

root = ET.fromstring(xml)
editions = root.findall('.//edition')
sorted_editions = sorted(editions, key=lambda e: e.attrib['language'])
for edition in sorted_editions:
    print(edition.attrib['language'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM