Golang : How to create new XML file ?
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
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
Tutorials
+12.3k Golang : Get constant name from value
+5.1k Golang : Convert Chinese UTF8 characters to Pin Yin
+7k Golang : Get final or effective URL with Request.URL example
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+3.5k Golang : Valued expressions and functions example
+10.5k Golang : Get remaining text such as id or filename after last segment in URL path
+15.2k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+3.8k Python : Find out the variable type and determine the type with simple test
+4.2k Golang : Get FX sentiment from website example
+18.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+9.9k Golang : How to determine a prime number?
+16.4k Golang : Upload/Receive file progress indicator