Can ElementTree be told to preserve the order of attributes?
Posted
by dmckee
on Stack Overflow
See other posts from Stack Overflow
or by dmckee
Published on 2010-04-29T23:48:50Z
Indexed on
2010/04/30
1:17 UTC
Read the original article
Hit count: 357
I've written a fairly simple filter in python using ElementTree to munge the contexts of some xml files. And it works, more or less.
But it reorders the attributes of various tags, and I'd like it to not do that.
Does anyone know a switch I can throw to make it keep them in specified order?
Context for this
I'm working with and on a particle physics tool that has a complex, but oddly limited configuration system based on xml files. Among the many things setup that way are the paths to various static data files. These paths are hardcoded into the existing xml and there are no facilities for setting or varying them based on environment variables, and in our local installation they are necessarily in a different place.
This isn't a disaster because the combined source- and build-control tool we're using allows us to shadow certain files with local copies. But even thought the data fields are static the xml isn't, so I've written a script for fixing the paths, but with the attribute rearrangement diffs between the local and master versions are harder to read than necessary.
This is my first time taking ElementTree for a spin (and only my fifth or sixth python project) so maybe I'm just doing it wrong.
Abstracted for simplicity the code looks like this:
tree = elementtree.ElementTree.parse(inputfile)
i = tree.getiterator()
for e in i:
e.text = filter(e.text)
tree.write(outputfile)
Reasonable or dumb?
Related links:
© Stack Overflow or respective owner