REXML attribute storage order

I am trying to create such XML using REXML

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

But I get (note that key / order of values)

<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 doesn't 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

same. It appears that REXML uses some kind of dictionary to store attributes ...

Can I do the required order: key / value?

+3
source share
5 answers

In XML, it doesn't matter what order the attributes are in. If you have a piece of XML processing code where it matters, then I would assume that the code was an error.

XML , : " , - ".

, , . ( ), REXML -:-). / , , , ( ).

, Ruby REXML, ( ) (REXML2?).

puts, , , write_element src/rexml/formatters/pretty.rb, "node.attributes.each_attribute do |attr|" - , .

(. ), , , , .

+6

ad-hoc REXML::Formatter, REXML. ruby-talk ml :

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)
+6

, , REXML, .

, , XML REXML . , XML; , REXML , libxml. , libxml , ruby ​​ , erb, XML-.

!

+1

gioele:

, , XML-.

8 script , - (, XML , ).

# 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
+1

. , XML. , diff. , , . XML - , , .

0

Source: https://habr.com/ru/post/1703642/


All Articles