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
+21.2k Golang : Get password from console input without echo or masked
+8.3k Golang : Check if integer is power of four example
+22.9k Golang : Test file read write permission example
+11.1k Golang : Web routing/multiplex example
+12.1k Golang : md5 hash of a string
+6.7k Golang : Skip or discard items of non-interest when iterating example
+5.4k Python : Delay with time.sleep() function example
+14.8k Golang : Normalize unicode strings for comparison purpose
+6.2k Linux/Unix : Commands that you need to be careful about
+9.5k Mac OSX : Get a process/daemon status information
+27.6k PHP : Convert(cast) string to bigInt
+27.5k Golang : Convert integer to binary, octal, hexadecimal and back to integer