What have you found for these years?

2012-03-12

simple plist parser with nokogiri

This should be simple and straightforward: plist.rb
require 'nokogiri'
require 'time'

module Plist
  module_function
  def parse xml
    fold_dict(Nokogiri::XML.parse(xml).root.xpath('./dict'))
  end

  def fold_dict dict
    dict.xpath('./key').inject({}){ |r, key|
      r[key.inner_text] = fold(key.next_element)
      r
    }
  end

  def fold_array array
    array.children.map{ |child| fold(child) }.compact
  end

  def fold element
    case element.name
    when 'dict'   ; fold_dict( element)
    when 'array'  ; fold_array(element)
    when 'integer'; element.inner_text.to_i
    when 'real'   ; element.inner_text.to_f
    when 'date'   ; Time.parse(element.inner_text)
    when 'false'  ; false
    when 'true'   ; true
    when 'string' ; element.inner_text
    when 'data'   ; element.inner_text
    end
  end
end

0 retries:

Post a Comment

Note: Only a member of this blog may post a comment.



All texts are licensed under CC Attribution 3.0