Created
November 5, 2019 20:56
-
-
Save kjk/abdf76b17b89f29219d43cf92a084dba to your computer and use it in GitHub Desktop.
Serialize a struct as XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// :collection Essential Go | |
package main | |
import ( | |
"encoding/xml" | |
"fmt" | |
"log" | |
) | |
// :show start | |
type People struct { | |
XMLName xml.Name `xml:"people"` | |
Person []Person `xml:"person"` | |
noteSerialized int | |
} | |
type Person struct { | |
Age int `xml:"age,attr"` | |
FirstName string `xml:"first-name"` | |
Address Address `xml:"address"` | |
} | |
type Address struct { | |
City string `xml:"city"` | |
State string `xml:"state"` | |
} | |
// :show end | |
func main() { | |
// :show start | |
people := People{ | |
Person: []Person{ | |
Person{ | |
Age: 34, | |
FirstName: "John", | |
Address: Address{City: "San Francisco", State: "CA"}, | |
}, | |
}, | |
noteSerialized: 8, | |
} | |
d, err := xml.Marshal(&people) | |
if err != nil { | |
log.Fatalf("xml.Marshal failed with '%s'\n", err) | |
} | |
fmt.Printf("Compact XML: %s\n\n", string(d)) | |
d, err = xml.MarshalIndent(&people, "", " ") | |
if err != nil { | |
log.Fatalf("xml.MarshalIndent failed with '%s'\n", err) | |
} | |
fmt.Printf("Pretty printed XML:\n%s\n", string(d)) | |
// :show end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment