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
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+36k Golang : Get file last modified date and time
+7.9k Golang : Grayscale Image
+16.9k Golang : Read integer from file into array
+9.1k Golang : Get curl -I or head data from URL example
+13.2k Golang : Convert(cast) int to int64
+7.7k Golang : Generate human readable password
+16.1k Golang : How to check if input from os.Args is integer?
+18.4k Golang : How to remove certain lines from a file
+5.9k Unix/Linux : How to open tar.gz file ?
+14.1k Javascript : Prompt confirmation before exit
+13.2k Golang : Skip blank/empty lines in CSV file and trim whitespaces example