package main
import (
"encoding/xml"
"log"
"io/ioutil"
)
type Post struct {
XMLName xml.Name `xml:"post"`
Id string `xml:"id,attr"`
Content string `xml:"content"`
Author Author `xml:"author"`
Comments []Comment `xml:"comments>comment"`
Xml string `xml:",innerxml"`
}
type Author struct {
Id string `xml:"id,attr"`
Name string `xml:",chardata"`
}
type Comment struct {
Id string `xml:"id,attr"`
Content string `xml:"content"`
Author Author `xml:"author"`
}
func main() {
defer func() {
if err := recover(); err != nil {
log.Fatal(err)
}
}()
post := Post{
Id: "1",
Content: "Hello World!",
Author: Author{
Id: "2",
Name: "mjy",
},
}
output, err := xml.MarshalIndent(&post, "", " ")
checkErr(err)
err = ioutil.WriteFile("post.xml", []byte(xml.Header+string(output)), 0644)
checkErr(err)
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}