Sorting Xml Files
Is it possible to sort XML files like the following: Bob Alice
<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:outputmethod="xml" /><xsl:templatematch="*"><xsl:copy><xsl:copy-ofselect="@*"/><xsl:apply-templatesselect="*"><xsl:sortselect="(@name | text())[1]"/></xsl:apply-templates></xsl:copy></xsl:template></xsl:stylesheet>
Solution 2:
Try this XSLT:
<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:outputmethod="xml" /><xsl:templatematch="@* | node()"><xsl:copy><xsl:apply-templatesselect="@* | node()"><xsl:sortselect="text() | @*"/></xsl:apply-templates></xsl:copy></xsl:template></xsl:stylesheet>
Solution 3:
You can sort nodes by removing them from the parent node, and re-inserting them in the intended order. For example:
defsort_tree(tree):
""" recursively sorts the given etree in place """for child in tree:
sort_tree(child)
sorted_children = sorted(tree, key=lambda n: n.text)
for child in tree:
tree.remove(child)
for child inreversed(sorted_children):
tree.insert(0, child)
tree = etree.fromstring(YOUR_XML)
sort_tree(tree)
print(etree.tostring(tree, pretty_print=True))
Solution 4:
You don't need to sort the entire xml dom. Instead take the required nodes into a list and sort them. Because we would need the sorted order while processing and not in file, its better done in run time. May be like this, using minidom.
import os, sys
from xml.dom import minidom
document = """\
<root>
<model name="ford">
<driver>Bob</driver>
<driver>Alice</driver>
</model><model name="audi">
<driver>Carly</driver>
<driver>Dean</driver>
</model>
</root>
"""
document = minidom.parseString(document)
elements = document.getElementsByTagName("model")
elements.sort(key=lambda elements:elements.attributes['name'])
Post a Comment for "Sorting Xml Files"