package main import ( "fmt" "os" "xml" ) type Book struct { XMLName xml.Name `xml:"BOOK"` Title string `xml:"attr"` Chapters []Chapter } type Chapter struct { XMLName xml.Name `xml:"CHAPTER"` Title string `xml:"innerxml"` Sections []Section } type Section struct { XMLName xml.Name `xml:"SECTION"` Title string } const filename = "test.xml" func main() { oldBook := Book{XMLName: xml.Name{"", "BOOK"}, Title: "Go", Chapters: []Chapter{ Chapter{XMLName: xml.Name{"", "CHAPTER"}, Title: "Chapter 1", Sections: []Section{ Section{XMLName: xml.Name{"", "SECTION"}, Title: "Section 1.1"}, Section{XMLName: xml.Name{"", "SECTION"}, Title: "Section 1.2"}}}, Chapter{XMLName: xml.Name{"", "CHAPTER"}, Title: "Chapter 2", Sections: []Section{ Section{XMLName: xml.Name{"", "SECTION"}, Title: "Section 2.1"}, Section{XMLName: xml.Name{"", "SECTION"}, Title: "Section 2.2"}}}}} out, err := os.Create(filename) if err != nil { fmt.Println(err); os.Exit(1) } err = xml.Marshal(out, oldBook) if err != nil { fmt.Println(err); os.Exit(1) } fmt.Fprintf(out, "\n") out.Close() in, err := os.Open(filename) if err != nil { fmt.Println(err); os.Exit(1) } var newBook Book err = xml.Unmarshal(in, &newBook) if err != nil { fmt.Println(err); os.Exit(1) } in.Close() fmt.Printf("oldBook: %#v\n", oldBook) fmt.Printf("newBook: %#v\n", newBook) }