github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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  	"github.com/shogo82148/std/encoding/xml"
     9  	"github.com/shogo82148/std/fmt"
    10  	"github.com/shogo82148/std/log"
    11  )
    12  
    13  const (
    14  	Unrecognized Size = iota
    15  	Small
    16  	Large
    17  )
    18  
    19  func Example_textMarshalXML() {
    20  	blob := `
    21  	<sizes>
    22  		<size>small</size>
    23  		<size>regular</size>
    24  		<size>large</size>
    25  		<size>unrecognized</size>
    26  		<size>small</size>
    27  		<size>normal</size>
    28  		<size>small</size>
    29  		<size>large</size>
    30  	</sizes>`
    31  	var inventory struct {
    32  		Sizes []Size `xml:"size"`
    33  	}
    34  	if err := xml.Unmarshal([]byte(blob), &inventory); err != nil {
    35  		log.Fatal(err)
    36  	}
    37  
    38  	counts := make(map[Size]int)
    39  	for _, size := range inventory.Sizes {
    40  		counts[size] += 1
    41  	}
    42  
    43  	fmt.Printf("Inventory Counts:\n* Small:        %d\n* Large:        %d\n* Unrecognized: %d\n",
    44  		counts[Small], counts[Large], counts[Unrecognized])
    45  
    46  	// Output:
    47  	// Inventory Counts:
    48  	// * Small:        3
    49  	// * Large:        2
    50  	// * Unrecognized: 3
    51  }