I wanted to quickly create a utility to format any XML data using golang's xml.MarshalIndent()
However this code
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type node struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",attr"`
Text string `xml:",chardata"`
Children []node `xml:",any"`
}
x := node{}
_ = xml.Unmarshal([]byte(doc), &x)
buf, _ := xml.MarshalIndent(x, "", " ") // prefix, indent
fmt.Println(string(buf))
}
const doc string = `<book lang="en">
<title>The old man and the sea</title>
<author>Hemingway</author>
</book>`
Produces
<book>
 
 

<title>The old man and the sea</title>
<author>Hemingway</author>
</book>
Notice the extraneous matter after the <book>
opening element.
- I've lost my attributes - why?
- I'd like to avoid gathering spurious inter-element chardata - How?