package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
)
type Post struct {
XMLName xml.Name `xml:"post"`
Id string `xml:"id,attr"`
Content string `xml:"content"`
Author Author `xml:"author"`
}
type Author struct {
Id string `xml:"id,attr"`
Name string `xml:",chardata"`
}
func main() {
post := Post{
Id: "1",
Content: "Hello World!",
Author: Author{
Id: "2",
Name: "Sau Sheong",
},
}
// output, err := xml.Marshal(&post) //无缩进
//美化后的XML
output, err := xml.MarshalIndent(&post, "", "\t\t")
if err != nil {
fmt.Println("Error marshalling to XML:", err)
return
}
err = ioutil.WriteFile("post.xml", []byte(xml.Header + string(output)), 0644)
if err != nil {
fmt.Println("Error writing XML to file:", err)
return
}
}
运行结果:
<?xml version="1.0" encoding="UTF-8"?>
<post id="1">
<content>Hello World!</content>
<author id="2">Sau Sheong</author>
</post>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)