Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7790457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T21:35:37+00:00 2026-06-01T21:35:37+00:00

I have a CSV that I like to save all my hash values on

  • 0

I have a CSV that I like to save all my hash values on it. I am using nokogiri sax to parse a xml document and then save it to a CSV.

The sax parser:

require 'rubygems'
require 'nokogiri'
require 'csv'

class MyDocument < Nokogiri::XML::SAX::Document

  HEADERS = [ :titles, :identifier, :typeOfLevel, :typeOfResponsibleBody, 
              :type, :exact, :degree, :academic, :code, :text ]

  def initialize
     @infodata = {}
     @infodata[:titles] = Array.new([])
  end

  def start_element(name, attrs)
    @attrs = attrs
    @content = ''
  end
  def end_element(name)
    if name == 'title'
      Hash[@attrs]["xml:lang"]
      @infodata[:titles] << @content
      @content = nil
    end
    if name == 'identifier'
       @infodata[:identifier] = @content
       @content = nil
    end
    if name == 'typeOfLevel'
       @infodata[:typeOfLevel] = @content
       @content = nil
    end
    if name == 'typeOfResponsibleBody'
       @infodata[:typeOfResponsibleBody] = @content
       @content = nil
    end
    if name == 'type'
       @infodata[:type] = @content
       @content = nil
    end
    if name == 'exact'     
       @infodata[:exact] = @content
       @content = nil
    end
    if name == 'degree'
       @infodata[:degree] = @content
       @content = nil
    end
    if name == 'academic'
       @infodata[:academic] = @content
       @content = nil
    end
    if name == 'code'
       Hash[@attrs]['source="vhs"']
       @infodata[:code] = @content 
       @content = nil
    end
    if name == 'ct:text'
       @infodata[:beskrivning] = @content
       @content = nil
    end 
  end
  def characters(string)
    @content << string if @content
  end
  def cdata_block(string)
    characters(string)
  end
  def end_document
    File.open("infodata.csv", "ab") do |f|
      csv = CSV.generate_line(HEADERS.map {|h| @infodata[h] })
      csv << "\n"
      f.write(csv)
    end
  end
end

creating new an object for every file that is store in a folder(47.000xml files):

parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
counter = 0

Dir.glob('/Users/macbookpro/Desktop/sax/info_xml/*.xml') do |item|
  parser.parse(File.open(item, 'rb'))
  counter += 1
  puts "Writing file nr: #{counter}"
end

The issue:
I dont get a new line for every new set of values. Any ideas?

3 xml files for trying the code:
https://gist.github.com/2378898
https://gist.github.com/2378901
https://gist.github.com/2378904

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T21:35:39+00:00Added an answer on June 1, 2026 at 9:35 pm

    You need to open the file using “a” mode (opening a file with “w” clears any previous content).

    Appending an array to the csv object will automatically insert newlines. Hash#values returns an array of the values, but it would be safer to force the order. Flattening the array will potentially lead to misaligned columns (e.g. [[:title1, :title2], ‘other-value’] will result in [:title1, :title2, ‘other-value’]). Try something like this:

    HEADERS = [:titles, :identifier, ...]
    
    def end_document
      # with ruby 1.8.7
      File.open("infodata.csv", "ab") do |f|
        csv = CSV.generate_line(HEADERS.map { |h| @infodata[h] })
        csv << "\n"
        f.write(csv)
      end
      # with ruby 1.9.x
      CSV.open("infodata.csv", "ab") do |csv|
        csv << HEADERS.map { |h| @infodata[h] }
      end
    end
    

    The above change can be verified by executing the following:

    require "csv"
    
    class CsvAppender
    
      HEADERS = [ :titles, :identifier, :typeOfLevel, :typeOfResponsibleBody, :type,
                  :exact, :degree, :academic, :code, :text ]
    
      def initialize
        @infodata = { :titles => ["t1", "t2"], :identifier => 0 }
      end
    
      def end_document
        @infodata[:identifier] += 1
    
        # with ruby 1.8.7
        File.open("infodata.csv", "ab") do |f|
          csv = CSV.generate_line(HEADERS.map { |h| @infodata[h] })
          csv << "\n"
          f.write(csv)
        end
        # with ruby 1.9.x
        #CSV.open("infodata.csv", "ab") do |csv|
        #  csv << HEADERS.map { |h| @infodata[h] }
        #end
      end
    
    end
    
    appender = CsvAppender.new
    
    3.times do
      appender.end_document
    end
    
    File.read("infodata.csv").split("\n").each do |line|
      puts line
    end
    

    After running the above the infodata.csv file will contain:

    "[""t1"", ""t2""]",1,,,,,,,,
    "[""t1"", ""t2""]",2,,,,,,,,
    "[""t1"", ""t2""]",3,,,,,,,,
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a csv that looks like this: blah,blah, blah, blah ect, ect,column 3
I have a CSV file that is formatted like: 0.0023709,8.5752e-007,4.847e-008 and I would like
I have a CSV dump from another DB that looks like this (id, name,
I have a large number of csv files that look like this below: xxxxxxxx
I have a Django form that is working fine. I'd like to save the
I have a script that generates a csv file using the following code: header('Content-type:
I have a csv file that has like 30,000 rows in it. It also
I have a csv file that looks like this: 603629,0,ATLV0008,Vendor1,1942.60,11/04/2010,1942.60,9/1-9/30/10,EFT-JP 603627,2,ATLV0008,Vendor1,1242.40,11/04/2010,1242.40,7/1-7/31/10,EFT-JP 600023,0,FLD4V0003,Vendor2,1950.00,06/15/2010,1950.00,6/14/10 Request,EFT-JP 600024,0,FLD4V0003,Vendor2,1800.00,06/15/2010,1800.00,6/14/10
I have a csv that looks like Deamon,Host,1:2:4,aaa.03 Pixe,Paradigm,1:3:5,11.us I need to read this
I have a CSV file that looks like this, where time is a UNIX

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.