writing csv into file

Discussion in 'Ruby' started by Alfred Pier, Apr 28, 2011.

  1. Alfred Pier

    Alfred Pier Guest

    Hello guys ! I'm new in Ruby....Hope you can help because i'm trying a
    lot and just can't see where is the problem..
    I have this xml, and not only this, i want just for any xml file that i
    might put :

    <?xml version="1.0"?>
    <records>
    <company>
    <id>p1</id>
    <name>Skoda</name>
    <price>10000</price>
    <stock>4</stock>
    <country>Czech Republic</country>
    </company>
    <company>
    <id>p2</id>
    <name>Mercedes</name>
    <price>50000</price>
    <stock>5</stock>
    <country>Germany</country>
    </company>
    <company>
    <id>p3</id>
    <name>Alfa Romeo</name>
    <price>18000</price>
    <stock>19</stock>
    <country>Italy</country>
    </company>
    <company>
    <id>p4</id>
    <name>Fiat</name>
    <price>1500</price>
    <stock>15000</stock>
    <country>Italy</country>
    </company>
    </records>


    AND USING THE CODE BELOW:

    require 'nokogiri'
    require 'pp'

    xmldoc = Nokogiri::XML(IO.read("xmlinputfile.xml"))
    columns = xmldoc.xpath('/*/*[position()=1]/*').map(&:name)

    print "give csv output file\n"
    csvoutputfile = gets.chomp
    File.open(csvoutputfile, 'w') do |f|
    rows =[]
    xmldoc.xpath('/*/*').each do |row_xml|
    row_values = []
    f.puts " #{rows << row_values}"
    row_xml.xpath('./*').each do |field|
    f.puts "#{row_values << field.text}"

    end
    end
    pp rows


    end




    I WANT TO CONVERT IT TO CSV FORMAT LIKE THIS:

    id,name,price,stock,country
    p1,Skoda,10000,4,Czech Republic,
    p2,Mercedes,50000,5,Germany,
     
    Alfred Pier, Apr 28, 2011
    #1
    1. Advertisements

  2. IMHO this is sufficient as XPath: '/*/*[1]/*'
    You should separate filling your data structure from doing CSV output
    above. Right now you are printing rows for every record!
    Again, you should separate filling your data structure from doing CSV
    output above (or completely get rid of "rows") e.g.

    puts row_xml.xpath('./*').map(&:text).join
    You are seeing output of that last line.
    I would also consider using CSV for writing because that will give you
    proper quoting

    CSV.open("foo.txt", "w", col_sep:",") do |csv|
    ...
    csv << row_xml.xpath('./*').map(&:text)
    ...
    end
    Do you use output redirection for your script?
    Please do NOT shout.

    robert

    --=20
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
     
    Robert Klemme, Apr 28, 2011
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.