Created
December 17, 2010 16:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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