Sorting xml file alphabetically by name tag

拈花ヽ惹草 提交于 2019-12-13 03:48:50

问题


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>

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"

Thanks for any help


回答1:


You really need to have XQuery or XSLT in your toolkit for this kind of job.

In XQuery:

<items>{
  for $i in //item order by $i/name return $i
}</items>

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>


来源:https://stackoverflow.com/questions/53473823/sorting-xml-file-alphabetically-by-name-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!