github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/encoding/xml/example_marshaling_test.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package xml_test 6 7 import ( 8 "github.com/shogo82148/std/encoding/xml" 9 "github.com/shogo82148/std/fmt" 10 "github.com/shogo82148/std/log" 11 ) 12 13 const ( 14 Unknown Animal = iota 15 Gopher 16 Zebra 17 ) 18 19 func Example_customMarshalXML() { 20 blob := ` 21 <animals> 22 <animal>gopher</animal> 23 <animal>armadillo</animal> 24 <animal>zebra</animal> 25 <animal>unknown</animal> 26 <animal>gopher</animal> 27 <animal>bee</animal> 28 <animal>gopher</animal> 29 <animal>zebra</animal> 30 </animals>` 31 var zoo struct { 32 Animals []Animal `xml:"animal"` 33 } 34 if err := xml.Unmarshal([]byte(blob), &zoo); err != nil { 35 log.Fatal(err) 36 } 37 38 census := make(map[Animal]int) 39 for _, animal := range zoo.Animals { 40 census[animal] += 1 41 } 42 43 fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras: %d\n* Unknown: %d\n", 44 census[Gopher], census[Zebra], census[Unknown]) 45 46 // Output: 47 // Zoo Census: 48 // * Gophers: 3 49 // * Zebras: 2 50 // * Unknown: 3 51 }