Golang encoding/xml.Unmarshal() function examples
package encoding/xml
Unmarshal parses the XML-encoded data and stores the result in the value pointed to by v (2nd parameter), which must be an arbitrary struct, slice, or string. Well-formed data that does not fit into v is discarded. See http://golang.org/pkg/encoding/xml/#Unmarshal for more detailed description.
Golang encoding/xml.Unmarshal() function usage examples
Example 1:
func Decode_xml(derr chan string, b []byte, i interface{}) bool {
e := xml.Unmarshal(b, i)
if e != nil {
derr<-"TOOLS/XML/DECODE: "+e.Error();
return false
}
return true
}
Example 2:
package main
import (
"encoding/xml"
"fmt"
)
type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
func main() {
str := `
<person id="13"><name><first>John</first><last>Doe</last></name><age>42</age><Married>false</Married><City>Hanga Roa</City><State>Easter Island</State><!-- Need more details. --></person>`
var p Person
err := xml.Unmarshal([]byte(str), &p)
if err != nil {
fmt.Println(err)
}
fmt.Println("First name : " + p.FirstName)
fmt.Println("Last name : " + p.LastName)
}
Output :
First name : John
Last name : Doe
See another example at https://www.socketloop.com/tutorials/read-parse-xml-file-go
Reference :
Advertisement
Something interesting
Tutorials
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+27.6k PHP : Convert(cast) string to bigInt
+9.2k Golang : How to control fmt or log print format?
+10.6k Golang : Get local time and equivalent time in different time zone
+11.1k Golang : Simple image viewer with Go-GTK
+9.8k Golang : Qt get screen resolution and display on center example
+27.7k PHP : Count number of JSON items/objects
+4.8k Facebook : How to place save to Facebook button on your website
+15.3k Golang : Delete certain files in a directory
+13.2k Golang : How to calculate the distance between two coordinates using Haversine formula
+16k Golang : Read large file with bufio.Scanner cause token too long error
+10k Golang : Channels and buffered channels examples