How do I re-sort an XML file in Ruby
I have a ruby method that performs a complex data collection and places the information in an XML file. However, I need to add a post-processing step to re-sort the results based on the text value of a particular element.
I have built the loops and added information to a hash in order to allow me to do this. What I'm having difficulty figuring out is how to loop through elements. I have tried examples in the REXML and XML libraries to no avail.
My XML file is structured like this:
<?xml version="1.0"?>
<Data>
<Apps>
<Master>
<VehicleType>Tractor</VehicleType>
<Make>International</Make>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
<Breakout1>Green</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>440K3</Part1>
</Sub>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
<Breakout1>Blue</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>ABC87S</Part1>
</Sub>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
开发者_开发知识库 <Breakout1>Green</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>440K4</Part1>
</Sub>
</Master>
</Apps>
</Data>
I need to re-sort those elements on "Breakout1", I just can't figure out how to loop through the elements.
The loop body is basically made up of simple nested conditionals where I test for the name of the element, then perform a specific action. Any help is appreciated.
You can use each_element to search for and loop over elements in REXML or get_elements to return an array. Both take an xpath expression to narrow down the elements. Is this what you need?:
require "rexml/document"
XML = '<Data>
<Apps>
<Master>
<VehicleType>Tractor</VehicleType>
<Make>International</Make>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
<Breakout1>Green</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>440K3</Part1>
</Sub>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
<Breakout1>Blue</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>ABC87S</Part1>
</Sub>
<Sub>
<Model>Model 1600</Model>
<Years>2003</Years>
<Breakout1>Green</Breakout1>
<Part1_PartType>Seat</Part1_PartType>
<Part1>440K4</Part1>
</Sub>
</Master>
</Apps>
</Data>'
doc = REXML::Document.new XML
doc.root.each_element('//Sub') { |sub| puts sub.get_text('Breakout1') }
sorted = doc.root.get_elements('//Sub').sort { |s1, s2| s1.get_text('Breakout1') <=> s2.get_text('Breakout1') }
I got this going:
# extract event information
xml = Nokogiri::XML File.open filename
xml.xpath('//Master').each do |elem|
for ele in elem.elements
# my sorting stuff here
end
end
精彩评论