Golang encoding/csv: Difference between revisions

From wikinotes
Tag: Reverted
Tag: Reverted
Line 61: Line 61:
var result Result
var result Result
xml.Unmarshall([]byte(encoded), &result)
xml.Unmarshall([]byte(encoded), &result)
fmt.Println(result.Page[0].Title.Text)
fmt.Println(result.Page[0].Title.Text) // Linux
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Deserializing -->
</blockquote><!-- Deserializing -->

Revision as of 02:46, 26 June 2022

Go's builtin module for encoding/decoding csv files.

NOTE:

go's builtin csv module does not conform to the normal encoding interface.


Serializing

data := [][]string{
    {"1", "2", "3"},
    {"4", "5", "6"},
}
writer := new(strings.Builder)
csvWriter := csv.NewWriter(writer)
csvWriter.WriteAll(data)
fmt.Println(writer.String())
// 1,2,3
// 4,5,6

Deserializing

data := `1,2,3
         4,5,6`
reader := csv.NewReader(strings.NewReader(data))
records, _ := reader.ReadAll()
fmt.Println(records[0][1]) // 2

XML is generally not homogenous.
Record each possible sub-element as a field on your object.
If an element can occur multiple times, declare it as an array.

encoded := `
  <mediawiki>
      <siteinfo>
          abc
      </siteinfo>
      <page>
          <title>Main Page</title>
      </page>
      <page>
          <title>Linux</title>
      </page>
  </mediawiki>
`

type Result struct {
    XMLName  xml.Name `xml:"mediawiki"` // root node
    SiteInfo string   `xml:"siteinfo"`  // only one 'siteinfo' element under 'mediawiki'
    Page     []Page   `xml:"page"`      // multiple 'page' elements under 'mediawiki'
}

type Page struct {
    Title string `xml:"title"`
}

var result Result
xml.Unmarshall([]byte(encoded), &result)
fmt.Println(result.Page[0].Title.Text)  // Linux