Created
March 6, 2024 21:12
-
-
Save adsr303/0e49746dd51ebbdbb8d1299c2f75ef68 to your computer and use it in GitHub Desktop.
Custom Go bool type with marshaling to Y/N
This file contains hidden or 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
package main | |
import ( | |
"encoding/xml" | |
"fmt" | |
) | |
type BoolYN bool | |
func (b BoolYN) MarshalXMLAttr(name xml.Name) (xml.Attr, error) { | |
attr := xml.Attr{Name: name} | |
if b { | |
attr.Value = "Y" | |
} else { | |
attr.Value = "N" | |
} | |
return attr, nil | |
} | |
func (b *BoolYN) UnmarshalXMLAttr(attr xml.Attr) error { | |
switch attr.Value { | |
case "Y": | |
*b = true | |
return nil | |
case "N": | |
*b = false | |
return nil | |
default: | |
return fmt.Errorf("Cannot convert value to BoolYN: %s", attr.Value) | |
} | |
} | |
type Root struct { | |
YesNo BoolYN `xml:",attr"` | |
TrueFalse bool `xml:",attr"` | |
} | |
func main() { | |
var r Root | |
if err := xml.Unmarshal([]byte(`<Root YesNo="Y" TrueFalse="true"/>`), &r); err != nil { | |
fmt.Printf("Could not unmarshal: %v\n", err) | |
return | |
} | |
fmt.Println(r) | |
b, err := xml.Marshal(r) | |
if err != nil { | |
fmt.Printf("Could not marshal: %v\n", err) | |
return | |
} | |
s := string(b) | |
fmt.Println(s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment