使用 golang 生成 xml 文件
相當簡單,這邊做個紀錄
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>