Minidom XML output - attributes in wrong order ?

  • Thread starter Peter Møllerud
  • Start date
P

Peter Møllerud

I'm very new to Python, so consider this a silly newbie question...
Anyway, I'm building a small application to generate a XML. Using document
from minidom, I'm doing something like :

from xml.dom.minidom import Document

doc = Document()

c = doc.createElement("sometest")
doc.appendChild(c)
tmp = doc.createElement("info")
tmp.setAttribute("vehicle", "car")
tmp.setAttribute("x-ray ", "100-1")
tmp.setAttribute("age", "30")
c.appendChild(tmp)
print doc.toprettyxml(indent=" ")

What it then prints out is :

<?xml version="1.0" ?>
<sometest>
<info age="30" vehicle="car" x-ray ="100-1"/>
</sometest>

What I expected was : <info vehicle="car" x-ray="100-1" age="30"/>

So it seems the dom module sorts the attributes alphabetically. Is there any
way I can prevent it from doing that ? What I want is to list them out in
the same order as they are added in the code...

Thanks,

Peter
 
M

Maxim Sloyko

So it seems the dom module sorts the attributes alphabetically. Is there any
way I can prevent it from doing that ? What I want is to list them out in
the same order as they are added in the code...

I don't know how to do what you ask, I'm just here to warn you that you
shouldn't rely on the order of attributes in the document in any way,
because this is implementation dependent.

If you need to preserve order of some items -- use child elements
instead of attributes.
 
S

Stefan Behnel

Peter said:
I'm very new to Python

then you might want to consider using ElementTree or lxml, not necessarily
minidom.

c = doc.createElement("sometest")
doc.appendChild(c)
tmp = doc.createElement("info")
tmp.setAttribute("vehicle", "car")
tmp.setAttribute("x-ray ", "100-1")
tmp.setAttribute("age", "30")
c.appendChild(tmp)
print doc.toprettyxml(indent=" ")

What it then prints out is :

<?xml version="1.0" ?>
<sometest>
<info age="30" vehicle="car" x-ray ="100-1"/>
</sometest>

What I expected was : <info vehicle="car" x-ray="100-1" age="30"/>

Attributes in XML are not ordered and no XML library will keep the order. All
you could do is serialise by hand, which is not that difficult either. Is
there any reason why you might want to keep the order?

Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top