Created
October 30, 2012 00:56
-
-
Save tourdedave/3977669 to your computer and use it in GitHub Desktop.
XML to CSV for Less Accounting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'nokogiri' | |
require 'csv' | |
@xml = Nokogiri::XML(open("Old-Accounting-System.xml")) | |
@csv = CSV.open("output.csv", "w") | |
def populate(opts = Hash.new(0)) | |
fields = [] | |
payload = [] | |
opts.each do |k,v| | |
fields << k | |
payload << v | |
end | |
@csv << CSV::Row.new(fields, payload) | |
end | |
def get_business_id_for(proposal_id) | |
@xml.xpath('//invoice').each do |line| | |
if line.text.include? proposal_id | |
return line.xpath('contact-id').text | |
end | |
end | |
end | |
fields = %w(account_number business_name) | |
@csv << CSV::Row.new(fields, fields) | |
@xml.xpath('//contact').each do |contact| | |
id = contact.xpath('id').text | |
business_name = contact.xpath('company-name').text | |
name = contact.xpath('name').text | |
if business_name.empty? | |
business_name = name | |
end | |
if name.empty? | |
name = "N/A" | |
end | |
populate( | |
account_number: id, | |
business_name: "#{business_name} (#{name})" | |
) | |
end | |
fields = [] | |
@csv << CSV::Row.new(fields, fields) | |
fields = %w(business_id proposal_id created_at type_of_work description quantity unit_price total) | |
@csv << CSV::Row.new(fields, fields) | |
@xml.xpath('//line-item').each do |line| | |
business_id = get_business_id_for(line.xpath('proposal-id').text) | |
if business_id.is_a? String | |
populate( | |
business_id: business_id, | |
proposal_id: line.xpath('proposal-id').text, | |
created_at: line.xpath('created-at').text, | |
type_of_work: line.xpath('line').text, | |
description: line.xpath('additional-description').text, | |
quantity: line.xpath('quantity').text, | |
unit_price: line.xpath('unit-price').text, | |
total: line.xpath('total').text | |
) | |
end | |
end | |
`open output.csv` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment