🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[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)) // <person id="13"> // <name> // <first>John</first> // <last>Doe</last> // </name> // <age>42</age> // <Married>false</Married> // <address> // <City>Hanga Roa</City> // <State>Easter Island</State> // </address> // <!-- Need more details. --> // </person> ``` ## 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 := ` <Person> <FullName>Grace R. Emlin</FullName> <Company>Example Inc.</Company> <Email where="home"> <Addr>gre@example.com</Addr> </Email> <Email where='work'> <Addr>gre@work.com</Addr> </Email> <Group> <Value>Friends</Value> <Value>Squash</Value> </Group> <City>Hanga Roa</City> <State>Easter Island</State> </Person> ` 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}} ```