Golang : How to create new XML file ?



Tags : golang XML

This is a follow up tutorial for XML and continue from previous tutorial on how to read XML file in Golang. In this tutorial, we will learn how to create new XML.

createxml.go

 package main

 import (
 "encoding/xml"
 "fmt"
 "os"
 "io"
 )

 func main() {

 type Staff struct {
 XMLName xml.Name `xml:"staff"`
 ID int `xml:"id"`
 FirstName string `xml:"firstname"`
 LastName string `xml:"lastname"`
 UserName string `xml:"username"`
 }

 type Company struct {
 XMLName xml.Name `xml:"company"`
 Staffs []Staff  `xml:"staff"`
 }


 v := &Company{}

 // add two staff details
 v.Staffs = append(v.Staffs, Staff{ID: 103, FirstName: "Adam", LastName: "Ng", UserName: "adamng"})
 v.Staffs = append(v.Staffs, Staff{ID: 108, FirstName: "Jennifer", LastName: "Loh", UserName: "jenniferloh"})

 filename := "newstaffs.xml"
 file, _ := os.Create(filename)

 xmlWriter := io.Writer(file)

 enc := xml.NewEncoder(xmlWriter)
 enc.Indent("  ", " ")
 if err := enc.Encode(v); err != nil {
 fmt.Printf("error: %v\n", err)
 }

 }

and the output in newstaffs.xml file should look like this

>more newstaffs.xml

 <company>
 <staff>
 <id>103</id>
 <firstname>Adam</firstname>
 <lastname>Ng</lastname>
 <username>adamng</username>
 </staff>
 <staff>
 <id>108</id>
 <firstname>Jennifer</firstname>
 <lastname>Loh</lastname>
 <username>jenniferloh</username>
 </staff>
 </company>

UPDATE : A reader asked if there is a "better" way to handle the deeper XML type? Such as cutting down the number of times you have to use the append() function.

Just wrap all the common/repetitive tasks into the AddStaff() method. See :

 package main

 import (
 "encoding/xml"
 "fmt"
 "io"
 "os"
 )

 // if variable name starts with small cap
 // for example : "tape" instead of "Tape"
 // the final value will not appear in XML

 type Thing struct {
 XMLName xml.Name `xml:"thing"`
 Tape string `xml:"tape"`
 // Tape string `xml:", innerxml"` -- keep it simple!
 }

 type Staff struct {
 XMLName xml.Name `xml:"staff"`
 ID int `xml:"id"`
 FirstName string `xml:"firstname"`
 LastName  string `xml:"lastname"`
 UserName  string `xml:"username"`
 TapeBrand Thing
 }

 type Company struct {
 XMLName xml.Name `xml:"company"`
 Staffs  StaffArray
 }

 type StaffArray struct {
 Staffs []Staff
 }

 func (s *StaffArray) AddStaff(sID int, sFName string, sLName string, sUName string, brandName string) {
 daThing := Thing{Tape: brandName}
 staffRecord := Staff{ID: sID, FirstName: sFName, LastName: sLName, UserName: sUName, TapeBrand: daThing}

 s.Staffs = append(s.Staffs, staffRecord)
 }

 func main() {

 v := Company{}

 // put a for loop here to add more data
 // this example will just add 2 rows of data.

 v.Staffs.AddStaff(103, "Adam", "Ng", "adamng", "scotch")
 v.Staffs.AddStaff(103, "Jennifer", "Loh", "jenniferloh", "sellotape")

 // sanity check - display on screen
 xmlString, err := xml.MarshalIndent(v, "", " ")

 if err != nil {
 fmt.Println(err)
 }

 fmt.Printf("%s \n", string(xmlString))

 // everything ok now, write to file.
 filename := "newstaffs.xml"
 file, _ := os.Create(filename)

 xmlWriter := io.Writer(file)

 enc := xml.NewEncoder(xmlWriter)
 enc.Indent("  ", " ")
 if err := enc.Encode(v); err != nil {
 fmt.Printf("error: %v\n", err)
 }

 }

Hope this tutorial can be useful in learning how to deal with XML file in Golang.

NOTES :

XML fields that have tags containing "-" will not be printed.

If a tag contains "name,attr", it uses name as the attribute name and the field value as the value, like version in the above example.

If a tag contains ",attr", it uses the field's name as the attribute name and the field value as its value.

If a tag contains ",chardata", it prints character data instead of element.

If a tag contains ",innerxml", it prints the raw value.

If a tag contains ",comment", it prints it as a comment without escaping, so you cannot have "--" in its value.

If a tag contains "omitempty", it omits this field if its value is zero-value, including false, 0, nil pointer or nil interface, zero length of array, slice, map and string.

  See also : Read a XML file in Go



Tags : golang XML

By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement