M
M
Magic Code2020-11-09 22:38:26
ruby
Magic Code, 2020-11-09 22:38:26

How to skip the first element and write the data opposite each other?

Goodnight!

There is a certain csv file, you need to take data from it and write it in two columns!

<?xml version="1.0" encoding="utf-16"?>
<SimpleGeoName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>6295630</Id>
  <Name>Earth</Name>
  <Children>
    <SimpleGeoName>
      <Id>6255146</Id>
      <Name>Africa</Name>
      <Children>
        <SimpleGeoName>
          <Id>2589581</Id>
          <Name>Algeria</Name>
          <Children>
            <SimpleGeoName>
              <Id>2508226</Id>
              <Name>Wilaya de Aïn Defla</Name>
              <Children />
              <FCode>ADM1</FCode>
              <CountryCode>DZ</CountryCode>


My code:

require "csv"
require "nokogiri"

data = File.open('continents.xml', encoding:'utf-8') { |file| Nokogiri::XML (file) }

CSV.open("continents.csv", "w") do |csv|
  # нужны 2 столбца
  csv << ["Name", "FCode"]  

 # Записываем под столбец Name
  data.xpath("//Name").each do |name|
    csv << name.text.split(',', 3)
  end
end


How can I skip the first tag <name>, writing data under the Name column and writing data under the second Fcode column ?

Guys, tell me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Magic Code, 2020-11-10
@Panda_Code

I figured it out, it remains only to skip some elements.

# frozen_string_literal: true

require "nokogiri"
require "csv"


data = File.open('continents.xml', encoding:'utf-8') { |file| Nokogiri::XML (file) }
name = data.xpath("//Name")
fcode = data.xpath("//FCode")
pool = name.zip(fcode)
  
CSV.open("continents.csv", "w") do |csv|
  csv << ["Name", "FCode"]

  pool.each do |name, fcode|
    csv << [name.text, fcode.text]
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question