Python lxml - 按子级排序

标签 python sorting lxml

我有一个非常大的 XML 文件,下面是一个小例子。 child 排序有捷径吗?我正在使用 Python 和 lxml。我想在处理数据之前打开文件时按 ID 排序,有人对如何执行此操作有建议吗?我打开了数据,并且以不同的格式写入数据,这种格式不容易提供排序,因此如果可能的话,我想预先对数据进行排序。感谢您的指导。

XML 示例:

<case>
    <id>2</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>3</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>1</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>

我想要这个:

<case>
<id>1</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>2</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>
<case>
<id>3</id>
<blah>someValue</blah>
<blahblah>someValue</blahblah>
</case>

最佳答案

您可以迭代所有 case 元素。然后创建一个包含所有 id 值的列表。对列表进行排序。然后迭代列表并始终输出 id 中具有该值的 case 元素。

这听起来不太有效,但这是我首先想到的。

更新:我想最好使用 id 值作为键将字典添加到列表中,并按这些键对列表进行排序。之后,您可以迭代列表并将现在排序的字典的值写入输出。

关于Python lxml - 按子级排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16942105/

相关文章:

python - 如何使用 Python 的 ElementTree 转义属性名称中的冒号?

python - 使用 Tornado RequestHandler 时最好的 REST 实现是什么

python - 如何调用产生的函数(python 2.7)

java - 在Java中递归地对数字的数字进行排序

arrays - 使用 Ruby 按组自定义排序数组

python - lxml.etree : Start tag expected, '<' 未找到,第 1 行,第 1 列

python - 如何在 Python 中获取两个 html 标签之间的所有内容?

python - 识别短文本的语言?

c++ - 合并 k 个排序列表超出时间限制(leetcode)

python - 在必须使用正则表达式在 html 文档中查找某些内容后重新使用 lxml 的强大功能的最佳方法