Process CSV and XML in Go
Process CSV and XML in Go
Choose a format to match the data contract. CSV stores tabular records and supports quoted commas and newlines; never parse general CSV by splitting on commas. XML represents named elements, attributes and nested content. Use the corresponding standard-library parser and check errors.
package main
import ( "bytes" "encoding/csv" "fmt" "strings")
func check(e error) { if e != nil { panic(e) }}
func main() { r := csv.NewReader(strings.NewReader("name,city\nAva,\"Paris, France\"\n")) rows, e := r.ReadAll() check(e) fmt.Println(rows[1][0]) fmt.Println(rows[1][1]) var b bytes.Buffer w := csv.NewWriter(&b) check(w.Write(rows[1])) w.Flush() check(w.Error()) fmt.Print(b.String())}ReadAll suits small trusted fixtures. For larger data use Read in a loop until io.EOF and enforce record and input limits; the default reader infers the field count from the first record. The writer quotes the comma-containing field. Flush and check Error because writes may be buffered. CSV quoting is not spreadsheet formula neutralization; handle that separately when exporting untrusted values.
Expected output:
AvaParis, FranceAva,"Paris, France"Map XML attributes and elements
package main
import ( "encoding/xml" "fmt")
func check(e error) { if e != nil { panic(e) }}
type Product struct { XMLName xml.Name `xml:"product"` ID int `xml:"id,attr"` Name string `xml:"name"`}
func main() { var p Product check(xml.Unmarshal([]byte(`<product id="7"><name>Tea & rice</name></product>`), &p)) fmt.Println(p.ID, p.Name) b, e := xml.Marshal(p) check(e) fmt.Println(string(b))}XMLName specifies the root element name; attr maps ID to an attribute, and Name maps to a child element. Marshal escapes special text characters. XML decoding is not full schema validation: check required values and impose input limits. Use a token-based decoder for large XML streams where appropriate.
Expected output:
7 Tea & rice<product id="7"><name>Tea & rice</name></product>Try it locally
Parse the CSV line "red,blue",2 using csv.Reader and print the first field and field count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 07: Process CSV and XML in Go
Check the lesson objective before moving on.
Why not use strings.Split on a CSV line?
Which XML tag option maps a field to an attribute?