Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A quick script to convert the XML from Android app "SMS Backup & Restore" into CSV.
#!/usr/bin/env ruby
# A quick script to convert the XML from Android app "SMS Backup & Restore" into CSV.
#
# Usage: $ ./sms-backup-to-csv.rb < PATH/TO/BACKUP/FILE.xml
require "nokogiri"
require "csv"
# Specify the backup file's attributes and data types.
COLUMNS = { "protocol" => :to_i, "address" => :to_s, "date" => :to_i, "type" => :to_i, "subject" => :to_s, "body" => :to_s, "toa" => :to_i, "sc_toa" => :to_i, "service_center" => :to_s, "read" => :to_i, "status" => :to_i, "locked" => :to_i, "date_sent" => :to_s, "readable_date" => :to_s, "contact_name" => :to_s }
# Read backup file from stdin and into Nokogiri.
backup = Nokogiri::XML ARGF.read
# Pluck out just the SMS nodes
messages = backup.css("sms")
# For each message, grab and convert each attribute specified above.
rows = messages.map { |m| COLUMNS.map {|k,v| m.attribute(k).content.method(v).call }}
# Write the data as a CSV to stdout.
CSV do |stdout|
stdout << COLUMNS.keys
rows.each {|r| stdout << r }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment