xml.Unmarshal, xml.Marshal, xml.MarshalIndent
func Unmarshal(data []byte, v any) error
func Marshal(v any) ([]byte, error)
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
type SyntaxError struct {
Msg string
Line int
}Unmarshal fills a tagged struct. Marshal and MarshalIndent emit XML that need not match the original spelling. A truncated document returns *xml.SyntaxError.
| Parameter | Description |
|---|---|
data, v | Unmarshal reads data into v. v should be a pointer to the destination value. |
v (Marshal) | The value to encode. Channels, functions, and maps cannot be marshaled and return an error. |
prefix, indent | MarshalIndent writes prefix at the start of each indented line and indent at each nesting level. This changes whitespace only in the output; it does not recover comments dropped during Unmarshal. |
Returns: Unmarshal returns nil on success. Marshal and MarshalIndent return the encoded bytes and an error. This example prints the SyntaxError with its type and message.
Errors
*xml.SyntaxError— Returned when the input is not well-formed XML. The truncated <box> document in this example reports unexpected EOF on line 1.
- The input has extra spaces and a comment. After Unmarshal, Marshal and MarshalIndent both omit the comment and the extra spaces. That is why this is not a semantic canonical form of the original bytes.
package main
import (
"encoding/xml"
"fmt"
)
type Item struct {
ID string `xml:"id,attr"`
Body string `xml:",chardata"`
}
type Box struct {
XMLName xml.Name `xml:"box"`
Items []Item `xml:"item"`
}
func main() {
in := []byte(`<box ><item id="a"><!--note-->one</item><item id="b">two</item></box>`)
var box Box
if err := xml.Unmarshal(in, &box); err != nil {
fmt.Println("unmarshal", err)
return
}
out, err := xml.Marshal(box)
fmt.Printf("%s %s %v\n", box.Items[0].ID, box.Items[0].Body, err)
fmt.Printf("%s\n", in)
fmt.Printf("%s\n", out)
indented, err := xml.MarshalIndent(box, "", " ")
fmt.Printf("%v\n%s\n", err, indented)
err = xml.Unmarshal([]byte(`<box>`), new(Box))
fmt.Printf("%T %v\n", err, err)
}Expected output
a one <nil>
<box ><item id="a"><!--note-->one</item><item id="b">two</item></box>
<box><item id="a">one</item><item id="b">two</item></box>
<nil>
<box>
<item id="a">one</item>
<item id="b">two</item>
</box>
*xml.SyntaxError XML syntax error on line 1: unexpected EOF
Related: XML Diff tool, XML formatter, encoding/json, Official encoding/xml