Golang encoding/xml.Encoder.EncodeElement() function example
package encoding/xml
EncodeElement writes the XML encoding of v to the stream, using start as the outermost tag in the encoding.
See the documentation for Marshal for details about the conversion of Go values to XML.
EncodeElement calls Flush before returning.
Golang encoding/xml.Encoder.EncodeElement() function usage example
package main
import (
"encoding/xml"
"fmt"
"os"
"reflect"
)
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"}
encoder := xml.NewEncoder(os.Stdout)
start := xml.StartElement{
Name: xml.Name{
Space: "",
Local: reflect.Indirect(reflect.ValueOf(v)).Type().Name(),
},
Attr: []xml.Attr{{xml.Name{"", "xmlns"}, "https://socketloop.com/xmldoc/2014-09-01/"}},
}
if err := encoder.EncodeElement(v, start); err != nil {
fmt.Println(err)
}
}
Output :
<Person xmlns="https://socketloop.com/xmldoc/2014-09-01/" 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>
Reference :
Advertisement
Something interesting
Tutorials
+39k Golang : How to iterate over a []string(array)
+9.8k Golang : Format strings to SEO friendly URL example
+22.5k Golang : Convert Unix timestamp to UTC timestamp
+33.6k Golang : How to check if slice or array is empty?
+5.9k Facebook : How to force facebook to scrape latest URL link data?
+12.3k Golang : Print UTF-8 fonts on image example
+11.8k Golang : convert(cast) float to string
+13.1k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.2k PHP : See installed compiled-in-modules
+30.4k Golang : How to verify uploaded file is image or allowed file types
+11.5k Golang : Generate DSA private, public key and PEM files example
+20.5k Golang : Pipe output from one os.Exec(shell command) to another command