一.生成XML
- 生成XML只要在学习下encoding/xml包下的Marshal()函数,结合输入流就可以完成xml文件生成
- 在encoding/xml中有常量,常量中是xml文档头
const ( // Header is a generic XML header suitable for use with the output of Marshal. // This is not automatically added to any output of this package, // it is provided as a convenience. Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n")
二.代码示例
- 使用Marshal()函数生成的[]byte没有格式化
- 使用MarshalIndent()可以对内容进行格式化
- 第一个参数:结构体对象
- 第二个参数:每行的前缀
- 第三个参数:层级缩进内容
type People struct { XMLName xml.Name `xml:"people"` Id int `xml:"id,attr"` Name string `xml:"name"` Address string `xml:"address"`}func main() { peo := People{Id: 123, Name: "smallming", Address: "北京海淀"} b, _ := xml.MarshalIndent(peo, "", " ") b = append([]byte(xml.Header), b...) ioutil.WriteFile("D:/peo.xml", b, 0666) fmt.Println("程序结束")}