xml

最后更新于:2022-04-02 02:43:36

[TOC] ## xml.Marshal / xml.MarshalIndent ``` type Address struct { City, State string } type Person struct { XMLName string `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Address `xml:"address"` Comment string `xml:",comment"` } v := &Person{ Id: 13, FirstName: "John", LastName: "Doe", Age: 42, Address: Address{ City: "Hanga Roa", State: "Easter Island", }, Comment: " Need more details. ", } output, err := xml.MarshalIndent(v, " ", " ") // 缩进 //output, err := xml.Marshal(v) // 不缩进 if err != nil { fmt.Printf("error: %v\n", err) } fmt.Printf("%+v\n", string(output)) // // // John // Doe // // 42 // false //
// Hanga Roa // Easter Island //
// //
``` ## xml.Unmarshal ``` type Email struct { Where string `xml:"where,attr"` Addr string } type Address struct { City, State string } type Result struct { XMLName xml.Name `xml:"Person"` Name string `xml:"FullName"` Phone string Email []Email Groups []string `xml:"Group>Value"` Address } v := Result{Name: "none", Phone: "none"} data := ` Grace R. Emlin Example Inc. gre@example.com gre@work.com Friends Squash Hanga Roa Easter Island ` err := xml.Unmarshal([]byte(data), &v) if err != nil { fmt.Printf("error: %v", err) return } fmt.Printf("%+v\n", v) // {XMLName:{Space: Local:Person} Name:Grace R. Emlin Phone:none Email:[{Where:home // Addr:gre@example.com} {Where:work Addr:gre@work.com}] Groups:[Friends Squash] A //ddress:{City:Hanga Roa State:Easter Island}} ```
';