The conversion of a CSV file to XML format can be necessary in many situations, such as data integration between applications or data transformation for processing in different systems. In this article, we will see how to create a Go program to convert a CSV file to XML.
Let's assume we have a CSV file called data.csv
with the following content:
name,age,city
Alice,30,New York
Bob,25,San Francisco
Charlie,35,Los Angeles
Now let's create the main code:
package main
import (
"encoding/csv"
"encoding/xml"
"fmt"
"os"
)
type Record struct {
Name string `xml:"name"`
Age string `xml:"age"`
City string `xml:"city"`
}
type Records struct {
XMLName xml.Name `xml:"records"`
Record []Record `xml:"record"`
}
func main() {
// Open the CSV file
csvFile, err := os.Open("data.csv")
if err != nil {
fmt.Println("Error opening the CSV file:", err)
return
}
defer csvFile.Close()
// Read the CSV file
reader := csv.NewReader(csvFile)
records, err := reader.ReadAll()
if err != nil {
fmt.Println("Error reading the CSV file:", err)
return
}
// Check if there are rows
if len(records) < 2 {
fmt.Println("The CSV file contains no data.")
return
}
// Extract data from the CSV and build the XML structures
var data Records
headers := records[0] // Headers
for _, row := range records[1:] {
record := Record{
Name: row[0],
Age: row[1],
City: row[2],
}
data.Record = append(data.Record, record)
}
// Write the XML file
xmlFile, err := os.Create("data.xml")
if err != nil {
fmt.Println("Error creating the XML file:", err)
return
}
defer xmlFile.Close()
encoder := xml.NewEncoder(xmlFile)
encoder.Indent("", " ")
err = encoder.Encode(data)
if err != nil {
fmt.Println("Error writing the XML file:", err)
return
}
fmt.Println("Conversion completed! XML file generated: data.xml")
}
Here is how the data.xml
file looks:
<records>
<record>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</record>
<record>
<name>Bob</name>
<age>25</age>
<city>San Francisco</city>
</record>
<record>
<name>Charlie</name>
<age>35</age>
<city>Los Angeles</city>
</record>
</records>
Conclusion
In this guide, we have seen how to convert a CSV file to XML using Go. This approach is highly scalable and can be adapted to various needs. If your CSV file has a different structure, you can simply update the Go structure definitions to suit your case.