Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Created December 17, 2010 16:43
Show Gist options
  • Save Phrogz/745244 to your computer and use it in GitHub Desktop.
Save Phrogz/745244 to your computer and use it in GitHub Desktop.
Reordering nodes in a Nokogiri XML document and getting the result as new XML
require 'nokogiri'
xml = <<ENDXML
<top>
<node1>
<value>mmm</value>
<value>zzz</value>
<value>ccc</value>
</node1>
<anothernode>
<value>zzz</value>
<value>ccc</value>
</anothernode>
</top>
ENDXML
doc = Nokogiri::XML(xml) do |config|
config.options = Nokogiri::XML::ParseOptions::NOBLANKS
end
node1 = doc.at_xpath('//node1')
sorted = node1.children.sort_by{ |n| n.text }
sorted.each{ |n| node1 << n }
puts doc
#=> <?xml version="1.0"?>
#=> <top>
#=> <node1>
#=> <value>ccc</value>
#=> <value>mmm</value>
#=> <value>zzz</value>
#=> </node1>
#=> <anothernode>
#=> <value>zzz</value>
#=> <value>ccc</value>
#=> </anothernode>
#=> </top>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment