Golang encoding/xml.Marshal() function examples
package encoding/xml
Marshal returns the XML encoding of v.
Marshal handles an array or slice by marshalling each of the elements. Marshal handles a pointer by marshalling the value it points at or, if the pointer is nil, by writing nothing. Marshal handles an interface value by marshalling the value it contains or, if the interface value is nil, by writing nothing. Marshal handles all other data by writing one or more XML elements containing the data. See ( http://golang.org/pkg/encoding/xml/#Marshal ) for more detailed description.
Golang encoding/xml.Marshal() function usage examples
Example 1 :
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() {
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
output, err := xml.Marshal(v)
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Println(string(output))
}
Output :
<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>
Example 2 :
func xmlEncode(i interface{}) (s string, err error) {
var buf []byte
buf, err = xml.Marshal(i)
if err != nil {
return
}
s = string(buf)
return
}
Reference :
See also : Golang encoding/xml.MarshalIndent() function example
Advertisement
Something interesting
Tutorials
+7.5k Golang : Dealing with struct's private part
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+15.2k JavaScript/JQuery : Detect or intercept enter key pressed example
+7k Golang : constant 20013 overflows byte error message
+11.6k Android Studio : Create custom icons for your application example
+9.1k Golang : Intercept and compare HTTP response code example
+16.6k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+20.2k Golang : Determine if directory is empty with os.File.Readdir() function
+14.2k Elastic Search : Mapping date format and sort by date
+13.7k Golang : Tutorial on loading GOB and PEM files
+5.2k Golang : Customize scanner.Scanner to treat dash as part of identifier
+6.9k Golang : Normalize email to prevent multiple signups example