package main import ( "encoding/xml" "fmt" "os" ) type Loc struct { Country string Province string } type City struct { Loc ID int `xml:"-"` // 不输出 People int `xml:"people,omitempty"` // 值为空时不输出 Name string `xml:"name"` } func main() { // // 序列化 // c := City{ID: 1, Name: "西安"} c.Loc = Loc{"中国", "陕西"} b, _ := xml.Marshal(c) os.Stdout.Write(b) // 中国陕西西安 fmt.Println() b, _ = xml.MarshalIndent(c, "", " ") fmt.Println(string(b)) // // 中国 // 陕西 // 西安 // // // 转义 // s := `233` // 将字符串中的 xml 保留字符转义 xml.Escape(os.Stdout, []byte(s)) // <x>233</x> }