I want to make a quick Ruby program that will allow me to read an XML file and sort a particular set of children, and then write it back sorted on disk. For example:
I want to sort from this XML file I made up:
<Nodes>
<Node1>
<Name>Fruits</Name>
<Properties>
<Property>
<Name>Orange<Name>
</Property>
<Property>
<Name>Vinegar<Name>
</Property>
<Property>
<Name>Apple<Name>
</Property>
</Properties>
</Node1>
<Node2>
<Name>Furniture</Name>
<Properties>
<Property>
<Name>Table</Name>
</Property>
<Property>
<Name>Desk</Name>
</Property>
<Property>
<Name>Bed</Name>
</Property>
</Properties>
</Node2>
</Nodes>
I want to sort the node Properties’s children alphabetically i.e.:
<Property>
<Name>Apple<Name>
</Property>
<Property>
<Name>Orange<Name>
</Property>
<Property>
<Name>Vinegar<Name>
</Property>
Is there a way I can do this quickly with Ruby?
As you’re already aware from your choice of tags, your tool of choice will be Nokogiri. I had some issue parsing your XML so I rewrote it as following:
And the corresponding code is: