按名称标签按字母顺序对xml文件进行排序 [英] Sorting xml file alphabetically by name tag
本文介绍了按名称标签按字母顺序对xml文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个大型的xml文件,格式如下:
I have several large xml files in the following format:
<item>
<name>Name 1</name>
<info>Details 1</info>
</item>
<item>
<name>Name 3</name>
<info>Details 3</info>
</item>
<item>
<name>Name 2</name>
<info>Details 2</info>
</item>
随着时间的推移,添加这些元素变得很丑陋.我想按名称标签按字母顺序对它们进行排序.我在这里搜索,发现了一些不同的python脚本,但它们对我不起作用.这是我尝试过的一个例子:
Over time of adding to these it has become ugly. I would like to sort them alphabetically by name tag. I have searched here and found a few different python scripts but they did not work for me. Here is one example of what I've tried:
import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
container = tree.find("item")
data = []
for elem in container:
key = elem.findtext("name")
data.append((key, elem))
data.sort()
container[:] = [item[-1] for item in data]
tree.write("test-out.xml")
print "File Written"
感谢您的帮助
推荐答案
您确实需要在工具包中包含XQuery或XSLT才能完成此类工作.
You really need to have XQuery or XSLT in your toolkit for this kind of job.
在XQuery中:
<items>{
for $i in //item order by $i/name return $i
}</items>
在XSLT(1.0或更高版本)中:
In XSLT (1.0 or later):
<items xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:for-each select="//item">
<xsl:sort select="name"/>
<xsl:copy-of select="."/>
</xsl:for-each>
</items>
这篇关于按名称标签按字母顺序对xml文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文