3

I try to generate such XML using REXML

<root>
  <add key='foo' value='bar'/>
</root>

But what I get is (notice that key/value order)

<root>
  <add value='bar' key='foo'/>
</root>

Code:

require 'rexml/document'
include REXML

doc = Document.new
doc.add_element('root')
el = doc.root.add_element('add')
el.add_attribute('key', 'foo')
el.add_attribute('value', 'bar')
puts doc

It does not matter if I write:

el.add_attribute('key', 'foo')
el.add_attribute('value', 'bar')

or

el.add_attribute('value', 'bar')
el.add_attribute('key', 'foo')

result is the same. Looks like REXML uses some dictionary to keep the attributes...

Can I enforce the desired order: key/value?

4
  • your second xml snippet is not well formatted.
    – Ray Lu
    Feb 22, 2009 at 10:59
  • Apart from readability, why does the attributs order matter?
    – Ray Lu
    Feb 22, 2009 at 11:03
  • Thanks for noticing a typo in xml snippet!
    – alex2k8
    Feb 22, 2009 at 11:56
  • I have a similar issue using REXML to do some processing on an existing XML file. The file is part of our source, and is checked into source code control. Whilst the order is not semantically relevant, it obscures the file history if I have to check in the modified file with the attributes rearranged.
    – Rob Walker
    Mar 4, 2010 at 22:16

5 Answers 5

6

In XML, it doesn't matter what order the attributes are in. If you have some piece of XML processing code where it does matter, then I would suggest that code was buggy.

From the XML spec here, note the phrase: "Note that the order of attribute specifications in a start-tag or empty-element tag is not significant".

In answer to your specific question on whether you can enforce a certain order, I don't believe so. I've never actually tried to do it (since it's unnecessary) but it seems unlikely the REXML people would waste time implementing such a non-feature :-). Since the key/value pairs are stored as a hash, their order is likely to be random (as far as you could tell from the alphabetic sequence of the keys).

Of course, since Ruby comes with the source code for REXML, you could (if desperate) replace or augment the included copy with your own version (REXML2 ?).

Since you're doing a simple puts, it's probably using the pretty formatter so check the start of the write_element code in src/rexml/formatters/pretty.rb where it performs the "node.attributes.each_attribute do |attr|" - you may find it's as simple as sorting that list before processing the elements.

You may also want to suggest to the developers (see here for the mailing list or here for bug reports and enhancement requests) that they make this an option in a future release but, if I were them, I'd simply say it was unnecessary.

2
  • 4
    Sure, the order does not matter from machine perspective. I need it for readability only. Actually I have to modify config file, and whould like to preserve formatting as much as possible.
    – alex2k8
    Feb 22, 2009 at 11:59
  • See updates on possible approaches (basically either forking for local use or trying to convince developers to add this feature).
    – paxdiablo
    Feb 22, 2009 at 12:06
6

You can try using an ad-hoc REXML::Formatter, without touching the REXML sources. A post on the ruby-talk ml suggests this code:

class OrderedAttributes < REXML::Formatters::Pretty
    def write_element(elm, out)
        att = elm.attributes

        class <<att
            alias _each_attribute each_attribute

            def each_attribute(&b)
                to_enum(:_each_attribute).sort_by {|x| x.name}.each(&b)
            end
        end

        super(elm, out)
    end
end

fmt = OrderedAttributes.new
fmt.write(doc, $stdout)
0
1

If you're modifying a config file and formatting is important, then it might be easier to read it in via REXML but modify via regexps.

Also, keep in mind that generating a lot of XML via REXML is incredibly slow. I had a site that had to both read and write a lot of XML; I found that for reading, REXML was fast enough, but for writing I had to use libxml. And actually, libxml was such a bear to install and the ruby libraries for it so immature, that I ended up using erb to just replace certain parts of already-written XML docs.

Good luck!

1

There are a number of valid reasons for wanting to preserve the sequence of attributes. The most significant is for validation of any program that modifies XML. When the sequence of attributes is maintained, it is possible to validate changes to a document with a simple diff. Preserving the sequence of information that is going to be displayed to a user is another. The XML standard took the path of using a hash-map for reasons of performance, but I think the absence of a feature in the specification to maintain sequence is a major limitation.

4
  • Validation is what XML Schema is for. Just like the XML standard, it doesn't care what order the attributes are placed in. Nov 23, 2012 at 22:56
  • John's response is puzzling. XML schema's validation capabilities are limited to the structure of the document, and do little to validate the content of the document. Also, to suggest that we do not wish to preserve order of attributes because this is not a capability of XML implies that we are limiting the requirements of the task to only what the technology can deliver out-of-the-box. The work I do solves real problems, and I use whatever is best to solve them, adapting it when needed.
    – user1157092
    Jul 30, 2013 at 17:36
  • In order to preserve attribute sequence, I write the code that outputs the XML document. Code that generates XML as an array of strings is more concise than most XML API's and at least 4 times faster than creating transient DOM objects.
    – user1157092
    Jul 30, 2013 at 17:53
  • It is the XML standard which states that attribute order does not matter, not XML schema. The XML InfoSet does not have a concept of attribute order. Jul 30, 2013 at 18:44
1

A simplified version of gioele's excellent solution:

If we make the list of attributes sorted, then output is deterministic, which is the important factor in avoiding spurious changes between versions of generated XML documents.

Adding these 8 lines to your script or application makes attributes ordered everywhere, without any need for further changes (eg. to modify the way you write the XML out, or find each place an element is implicitly converted to a string and change it to use the formatter).

# make REXML sort attributes by name so output is deterministic
module REXML
  class Attributes
    alias _each_attribute each_attribute
    def each_attribute(&b)
      to_enum(:_each_attribute).sort_by {|x| x.name}.each(&b)
    end
  end
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.