need help sorting hashes and yaml

B

Bucco

I have an xml file that looks something like this:
<action>
<date item="052906">
<task>Some task</task>
<task>Some other task</task>
</date>
<date item="053006">
... more tasks
</date>
</action>

I am trying to sort these task files into yaml that looks like this:
---
date:
052906:
- Some task
- Some other task
.... and so on for each date/task

I have done the following so far:
require 'xmlsimple'
require 'yaml'
doc = XmlSimple.xml_in("Some file.xml", {'KeyAttr' => 'item'})
puts doc.to_yaml


Although this prints out the correct format, the dates are unsorted.
And some of the dates are in quotes while others are not quoted in the
yaml output. I also tried the follwoing:

puts doc.sort.to_yaml

This sorts the hash into multiple arrays which then adds extra dashes
to the yaml output, but the date order is sorted correctly.

So my question is how to sort the hash so that the dates are read in
the correct order when outputted to yaml, but also keep the hash format
and not convert it to an array to sort?

Thanks in advance:)
SA
 
T

Trans

I pretty sure YAML has support for the secondary YAML type of ordered
map. Try this:

date: !omap
- 052906:
- Some task
- Some other task
...

Going the other way around of course is trickier but you should be able
to reuse YAML's omap class.

T.
 
B

Bucco

The problem I am having is sorting out each days task by date from xml
and then printing them back out in a yaml format. xml_simple pulls the
xml into a hash with the date keys in random order. I need to re-order
the date keys, and then print them to yaml with the correct tasks
underneath each date.

Thanks:)

SA
 
T

Trans

xml_simple pulls the xml into a hash with the date keys in random order.

I wouldn't use xml_simple than since that isn't good behavior --XML
documents are order significant. I'm actually suprised it uses a hash.
You might consider using REXML instead. It's pretty easy to traverse a
document.

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top