Standard library / encoding/xml
encoding/xml.Marshal()
Encodes Go values into XML. Struct tags control element names and attributes; unsupported values return errors. Expected stdout: '<user id="7"></user>\n'.
Formal Syntax & Structure
go syntaxgo
func Marshal(v any) ([]byte, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| v | any | Value to encode or pointer to the destination for decoding. |
Return Value
([]byte, error)
Resulting bytes (possibly partial for decoding) and error.
Working Example
Example Snippetgo
package main
import ( "encoding/xml" "fmt")
func must(e error) { if e != nil { panic(e) }}
func main() { p, e := xml.Marshal(struct { XMLName xml.Name `xml:"user"` ID int `xml:"id,attr"` }{ID: 7}) must(e) fmt.Println(string(p))}