Golang encoding/xml.Encoder.EncodeToken() function example
package encoding/xml
EncodeToken writes the given XML token to the stream. It returns an error if StartElement and EndElement tokens are not properly matched.
EncodeToken does not call Flush, because usually it is part of a larger operation such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked during those), and those will call Flush when finished. Callers that create an Encoder and then invoke EncodeToken directly, without using Encode or EncodeElement, need to call Flush when finished to ensure that the XML is written to the underlying writer.
EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token in the stream.
Golang encoding/xml.Encoder.EncodeToken() 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)
newtoken := xml.StartElement{
Name : xml.Name{
Space: "",
Local: "location",
},
}
if err := encoder.EncodeToken(newtoken); err != nil {
fmt.Println(err)
}
start := xml.StartElement{
Name: xml.Name{
Space: "",
Local: reflect.Indirect(reflect.ValueOf(v)).Type().Name(),
},
Attr: []xml.Attr{{xml.Name{"", "xmlns"}, "http://localhost/xmldoc/2014-09-01/"}},
}
if err := encoder.EncodeElement(v, start); err != nil {
fmt.Println(err)
}
}
Output :
<location>
<---- newtoken
<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
+9.9k Golang : Function wrapper that takes arguments and return result example
+12.7k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+15.4k Golang : Find location by IP address and display with Google Map
+8.8k Golang : Executing and evaluating nested loop in html template
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+6.9k How to let Facebook Login button redirect to a particular URL ?
+4.8k Facebook : How to place save to Facebook button on your website
+17.5k Golang : Linked list example
+7.8k Swift : Convert (cast) String to Double
+6.9k Golang : How to solve "too many .rsrc sections" error?
+6.1k Golang : Missing Subversion command
+12.4k Elastic Search : Return all records (higher than default 10)