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
+10.6k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+11.3k Golang : Byte format example
+6.1k Golang : Dealing with backquote
+40.5k Golang : Convert to io.ReadSeeker type
+13.5k Golang : Count number of runes in string
+12.3k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+13.2k Golang : Convert(cast) int to int64
+34.1k Golang : Create x509 certificate, private and public keys
+37.7k Golang : Comparing date or timestamp
+25k Golang : Create PDF file from HTML file
+11.6k Android Studio : Create custom icons for your application example
+8.4k Golang : Generate Datamatrix barcode