Golang : delete and modify XML file content
In our two previous tutorials on how to read XML file and how to create XML file, we have forgotten to show you how to modify and delete XML content :P
In this tutorial, we will use the standard library function to achieve the followings :
Read an existing XML file(Employees.xml)
Map the data to structs
Add one new record
Delete one record from the map
Update the new record
Save the date to a new XML file(LatestEmployees.xml)
Employees.xml
<?xml version="1.0"?>
<company>
<staff>
<id>101</id>
<firstname>Derek</firstname>
<lastname>Young</lastname>
<username>derekyoung</username>
</staff>
<staff>
<id>102</id>
<firstname>John</firstname>
<lastname>Smith</lastname>
<username>johnsmith</username>
</staff>
</company>
This is the full source code :
modifyxml.go
package main
import (
"fmt"
"io/ioutil"
"os"
"encoding/xml"
"io"
)
type Staff struct {
XMLName xml.Name `xml:"staff"`
ID int `xml:"id"`
FirstName string `xml:"firstname"`
LastName string `xml:"lastname"`
UserName string `xml:"username"`
}
var staffmap map[string]Staff
type Company struct {
XMLName xml.Name `xml:"company"`
Staffs []Staff `xml:"staff"`
}
func (s Staff) String() string {
return fmt.Sprintf("\t ID : %d - FirstName : %s - LastName : %s - UserName : %s \n", s.ID, s.FirstName , s.LastName, s.UserName)
}
func (s Staff) IDnum() int {
return s.ID
}
func (s Staff) FName() string {
return s.FirstName
}
func (s Staff) LName() string {
return s.LastName
}
func (s Staff) UName() string {
return s.UserName
}
func main() {
xmlFile, err := os.Open("Employees.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
XMLdata, _ := ioutil.ReadAll(xmlFile)
var c Company
xml.Unmarshal(XMLdata, &c)
// add one new record - we will modify this record in the map later
c.Staffs = append(c.Staffs, Staff{ID: 103, FirstName: "Adam", LastName: "Ng", UserName: "huh?"})
staffmap = make(map[string]Staff)
// populate the map
for _, staff := range c.Staffs {
staffmap[staff.FName()] = Staff{ID : staff.IDnum(), FirstName : staff.FName(), LastName : staff.LName(), UserName : staff.UName()}
}
fmt.Println("Map BEFORE delete operation :")
fmt.Println(staffmap)
delete(staffmap,"Derek") // remove Derek from staffs
fmt.Println("Map AFTER delete operation :")
fmt.Println(staffmap)
// modify staffmap["Adam"] - change ID to 108 and fix the huh? username
staffmap["Adam"] = Staff{ID: 108, FirstName: "Adam", LastName: "Ng", UserName: "adamng"}
fmt.Println("Map AFTER UPDATE operation :")
fmt.Println(staffmap)
// write to LatestEmployees.xml
v := &Company{}
for _, i := range staffmap {
v.Staffs = append(v.Staffs, staffmap[i.FName()]) // remember we declared map[string]Staff above
}
filename := "LatestEmployees.xml"
file, _ := os.Create(filename)
xmlWriter := io.Writer(file)
encoder := xml.NewEncoder(xmlWriter)
encoder.Indent(" ", " ")
if err := encoder.Encode(v); err != nil {
fmt.Printf("error : %v\n", err)
}
encoder.Flush()
fmt.Printf("Write operation to %s completed\n", filename)
}
Executing modifyxml.go will produce the following output :
Map BEFORE delete operation :
map[Derek: ID : 101 - FirstName : Derek - LastName : Young - UserName : derekyoung
John: ID : 102 - FirstName : John - LastName : Smith - UserName : johnsmith
Adam: ID : 103 - FirstName : Adam - LastName : Ng - UserName : huh?
]
Map AFTER delete operation :
map[Adam: ID : 103 - FirstName : Adam - LastName : Ng - UserName : huh?
John: ID : 102 - FirstName : John - LastName : Smith - UserName : johnsmith
]
Map AFTER UPDATE operation :
map[John: ID : 102 - FirstName : John - LastName : Smith - UserName : johnsmith
Adam: ID : 108 - FirstName : Adam - LastName : Ng - UserName : adamng
]
Write operation to LatestEmployees.xml completed
and the content of LatestEmployees.xml :
<company>
<staff>
<id>102</id>
<firstname>John</firstname>
<lastname>Smith</lastname>
<username>johnsmith</username>
</staff>
<staff>
<id>108</id>
<firstname>Adam</firstname>
<lastname>Ng</lastname>
<username>adamng</username>
</staff>
</company>
Hope this tutorial will be helpful to those learning Go and XML.
Note :
There should be better 3rd party solution to handle XML file in Golang. This tutorial uses the standard library.
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
+9.7k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+6.1k Golang : Pat multiplexer routing example
+5.5k Golang : Map within a map example
+5.3k PageSpeed : Clear or flush cache on web server
+5k Golang : Find change in a combination of coins example
+9.2k Golang : Edge detection with Sobel method
+10.2k Golang : Intercept and process UNIX signals example
+13.4k Golang : How to determine if user agent is a mobile device example
+13.4k Golang : Recombine chunked files example
+19.2k Golang : How to get struct tag and use field name to retrieve data?
+10.3k Golang : Characters limiter example
+22.5k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date