我想將標簽中的空值映射到物件中的空值,例如我有這個 xml
<Address>
<city>city</city>
<streetNumber></streetNumber>
</Address>
我的型別是
type Address struct{
city string `xml:"city"`
streetNumber *int `xml:"streetNumber"`
}
在這種情況下,streetNumber 是 0,但是當我從 xml 中洗掉標簽 streetNumber 時,它的值為 nil 是否可以將 streetNumber 標簽映射到 nil 當它為空時?
uj5u.com熱心網友回復:
您可能想看看streetNumber使用自定義編組制作自己的型別,就像他們在這里使用時間格式所做的那樣:
https ://www.programming-books.io/essential/go/custom-xml-marshaling-aa8105fe264b4b198647cbc718480ba1
我傾向于 int Valid bool 組合,但你可以做一個 int 指標。
編輯:更新以包括元帥/解組的潛在實作。
type Address struct {
City string `xml:"city"`
StreetNumber StreetNumber `xml:"streetNumber"`
}
type StreetNumber struct {
Value int
Valid bool
}
func (s StreetNumber) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
// If the address is null/unset/invalid, we serialize an empty string as the value.
v := ""
if s.Valid {
// The address has a value so we convert the integer to string.
v = strconv.Itoa(s.Value)
}
// Encode the string `v` to the XML element.
return e.EncodeElement(v, start)
}
func (s *StreetNumber) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
// Assume the value is invalid so we can just shortcut out.
s.Valid = false
s.Value = 0;
var v string
if err := d.DecodeElement(&v, &start); err != nil {
// Forward the error if it failed to decode the raw XML
return err
}
if v == "" {
// The value was empty, but this is just the 3rd null state, not an error.
return nil
}
i, err := strconv.Atoi(v)
if err != nil {
// The element value was not an integer so this is an invalid state -- forward the error.
return err
}
// The street number was a valid integer.
s.Valid = true
s.Value = i
return nil
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480236.html
