Tuesday, 15 April 2014

python - Is it possible to stop ElementTree from ordering my XML keys when writing -



python - Is it possible to stop ElementTree from ordering my XML keys when writing -

i having problem xml creator, generating whole bunch of info based on objects coming in maya , best if have attribute keys generated in file in order written in rather (very annoyingly) having them alphabetically ordered.

i populate elements so:

bodies = et.subelement(root, "bodies") myrp = [et.element("object", name=str("rootpoint"))] mybodies = [et.element("object", name=str(cobj), type=checkcollisiontype(cobj), padding="-2.5") cobj in cobjects] bodies.extend(myrp) bodies.extend(mybodies)

and write them so:

unformattedfile = et.elementtree(root) unformattedfile.write(filepath) prettyprintxml(filepath)

my result should this:

<body name="" enabled="" template=""> <object name="" /> <object name="" collision_type="" padding=""/> </body>

but after written element tree this:

<bodies> <body enabled="" name="" template=""> <object name=""/> <object name="" padding="" type=""/> </bodies>

for readability , generality preserve original order. found someones re-work of elementtree module messed lot of things

i have scoured net , havent been able find viable solution yet.

any help appreciated.

cheers

just in case has similar issue , looking reply made myself little hack around issue.

although not matter order of attributes in xml files our scheme @ work preferable. in end did tag each attribute letter. a, b etc. since dictionary ordered in alphabetical order worked me.

for example:

myshadowmeshes = et.element("object", aname=str(sobj), benabled="true", cshadow_caster='true')

what did create function replaces occurrences of these names right name:

def findanddeletecaps(filepath): # toreplace specifies items replace , # e.g. aname replaced name, btype replaced type toreplace = {"aname":"name", "benabled":"enabled", "btype":"type", "cshadow_caster":"shadow_caster", "ctemplate":"template", "cpadding":"padding", "cmaterial":"material"} # read in file string , open written texttoreplace = open(filepath).read() writefile = open(filepath,"w") # run through dictionary using original key , new text utilize original, new in toreplace.iteritems(): texttoreplace = texttoreplace.replace(original, new) # replace specified text writefile.write(texttoreplace) writefile.close()

that workaround hope finds useful :)

cheers,

ben

python xml order elementtree

No comments:

Post a Comment