Skip to content

Instantly share code, notes, and snippets.

@tonyblaze27
Forked from ablwr/xml_to_csv.rb
Created April 15, 2019 14:07
Show Gist options
  • Select an option

  • Save tonyblaze27/c3050cf150b4eb6ea19800c96d4729a2 to your computer and use it in GitHub Desktop.

Select an option

Save tonyblaze27/c3050cf150b4eb6ea19800c96d4729a2 to your computer and use it in GitHub Desktop.

Revisions

  1. @ablwr ablwr created this gist Sep 22, 2016.
    22 changes: 22 additions & 0 deletions xml_to_csv.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    require 'csv'
    require 'nokogiri'

    xml = File.read('hello.xml')
    doc = Nokogiri::XML(xml)

    all_the_things = []

    doc.xpath('//file').each do |file|
    title = file.xpath("./title").first.text
    filename = file.xpath("./name").first.text
    identifier = file.xpath("./identifier/*[contains(text(), 'My display ID')]").text
    secret = file.xpath("./identifier/secret").attr('secret').text
    all_the_things << [title, filename, identifier, secret]
    end

    CSV.open('new_file.csv', 'wb' ) do |row|
    row << ['title', 'filename', 'identifier', 'secret']
    all_the_things.each do |data|
    row << data
    end
    end