Python 以递归方式按和标记和属性对 XML 元素进行排序 [英] Python sort XML elements by and tag and attributes recursively

查看:24
本文介绍了Python 以递归方式按和标记和属性对 XML 元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我正在尝试使用一些规则对 XML 进行排序.
我的例子:

I am new to Python and I am trying to sort XML with some rules.
My example:

<?xml version="1.0"?>
<data>
    <e2 id="3" name="name3">
        <e12 num="num12" desc="desc12"/>
        <e12 num="num12" desc="desc11"/>
        <e11 num="num1" desc="desc1"/>
    </e2>
    <e2 id="2" name="name2">
        <e11 num="num1" desc="desc1"/>
    </e2>
    <e1 id="1" name="name1">
        <e12 num="num12" desc="desc12"/>
        <e11 num="num4" desc="desc4"/>
    </e1>
</data>

我的规则是:
1)按名称对各个元素中的每个属性进行排序
2) 排序元素
* 按标签名称(如果没有属性)
* 如果标签名称与其属性顺序相同

my rules are:
1) sort every attribute by name in respective element
2) sort elements
* by tag name (if no attributes)
* if tag name same by their attribute order

就我而言,我需要先对 e1 进行排序,然后对 e2 进行排序,
因为我有 2 个 e2 元素,所以我需要分别按它们的属性名称对它们进行排序,比如一个有 id=2,第二个有 id=3,所以顺序应该按 id 值完成.
所需的输出 XML 将如下所示:

in my case i need to sort first e1 and then e2,
since i have 2 e2 element i need to sort them by their attribute name respectively, like one has id=2 the second one has id=3 so the order should done by id value.
the desired output XML would look like this :

<?xml version="1.0"?>
<data>
    <e1 id="1" name="name1">
        <e11 desc="desc4" num="num4"/>
        <e12 desc="desc12" num="num12"/>
    </e1>
    <e2 id="2" name="name2">
        <e11 desc="desc1" num="num1"/>
    </e2>
    <e2 id="3" name="name3">
        <e11 num="num1" desc="desc1"/>
        <e12 desc="desc11" num="num12"/>
        <e12 desc="desc12" num="num12"/>
    </e2>
</data>

任何建议或想法如何做到这一点?
谢谢.

any advice or idea how to do this ?
Thank you.

推荐答案

您可以使用 ElementTree 对 XML 进行排序.在我的示例中,我首先按标签名称对其进行排序,然后按属性名称"的值对其进行排序,然后按标签名称和属性desc"的值对子元素进行排序

You can sort your XML with ElementTree. In my example I sort it first by the tag-name and second by the value of the attribut 'name' and the child elements by tag-name and the value of the attribut 'desc'

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstr))
root = tree.getroot()

# sort the first layer
root[:] = sorted(root, key=lambda child: (child.tag,child.get('name')))

# sort the second layer
for c in root:
    c[:] = sorted(c, key=lambda child: (child.tag,child.get('desc')))

xmlstr = ET.tostring(root, encoding="utf-8", method="xml")
print(xmlstr.decode("utf-8"))

这个打印

<data>
<e1 id="1" name="name1">
    <e11 desc="desc4" num="num4" />
    <e12 desc="desc12" num="num12" />
</e1>
<e2 id="2" name="name2">
    <e11 desc="desc1" num="num1" />
</e2>
<e2 id="3" name="name3">
    <e11 desc="desc1" num="num1" />
    <e12 desc="desc11" num="num12" />
    <e12 desc="desc12" num="num12" />
</e2>
</data>

这篇关于Python 以递归方式按和标记和属性对 XML 元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆