github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/encoding/xml/example_text_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 "encoding/xml" 9 "fmt" 10 "log" 11 "strings" 12 ) 13 14 type Size int 15 16 const ( 17 Unrecognized Size = iota 18 Small 19 Large 20 ) 21 22 func (s *Size) UnmarshalText(text []byte) error { 23 switch strings.ToLower(string(text)) { 24 default: 25 *s = Unrecognized 26 case "small": 27 *s = Small 28 case "large": 29 *s = Large 30 } 31 return nil 32 } 33 34 func (s Size) MarshalText() ([]byte, error) { 35 var name string 36 switch s { 37 default: 38 name = "unrecognized" 39 case Small: 40 name = "small" 41 case Large: 42 name = "large" 43 } 44 return []byte(name), nil 45 } 46 47 func Example_textMarshalXML() { 48 blob := ` 49 <sizes> 50 <size>small</size> 51 <size>regular</size> 52 <size>large</size> 53 <size>unrecognized</size> 54 <size>small</size> 55 <size>normal</size> 56 <size>small</size> 57 <size>large</size> 58 </sizes>` 59 var inventory struct { 60 Sizes []Size `xml:"size"` 61 } 62 if err := xml.Unmarshal([]byte(blob), &inventory); err != nil { 63 log.Fatal(err) 64 } 65 66 counts := make(map[Size]int) 67 for _, size := range inventory.Sizes { 68 counts[size] += 1 69 } 70 71 fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n", 72 counts[Small], counts[Large], counts[Unrecognized]) 73 74 // Output: 75 // Inventory Counts: 76 // * Small: 3 77 // * Large: 2 78 // * Unrecognized: 3 79 }