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
+14.2k Elastic Search : Mapping date format and sort by date
+8k Golang : Handle Palindrome string with case sensitivity and unicode
+23.1k Golang : Randomly pick an item from a slice/array example
+8.8k Golang : Random integer with rand.Seed() within a given range
+20.2k Golang : How to get struct tag and use field name to retrieve data?
+8.6k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+26.1k Mac/Linux and Golang : Fix bind: address already in use error
+31.6k Golang : Get local IP and MAC address
+10.2k Golang : How to profile or log time spend on execution?
+9.3k Golang : How to get username from email address
+8.3k Useful methods to access blocked websites
+17.7k Golang : Read data from config file and assign to variables