xml - 去 XML 解析 : set missing attributes to "true"

标签 xml go

下面的片段,

package main
import (
    "encoding/xml"
    "fmt"
)

func main() {
    var r struct {
        Item []struct {
            Value string `xml:"value,attr"`
            Flag bool `xml:"flag,attr"`
        } `xml:"item"`
    }
    xml.Unmarshal([]byte(`
        <result>
            <item value="1" flag="false" />
            <item value="2" flag="true" />
            <item value="3" />
        </result>`,
    ), &r)
    fmt.Printf("%+v\n", r)
}

会打印出如下结果:

{Item:[{Value:1 Flag:false} {Value:2 Flag:true} {Value:3 Flag:false}]}

在某些元素中,flag 属性将丢失(例如上面的第 3 项),但我希望它采用默认值 true,而不是 假的

  1. 我不能在构造函数中分配它,因为我不知道数组中元素的数量。
  2. 我不能使用实现了 UnmarshalerAttr 的自定义类型并在解码期间分配,因为如果该属性丢失,UnmarshalXMLAttr 将不会运行。
  3. 我可以将其设为一个指针,然后检查是否为 nil,然后为 true,但这太粗暴且容易出错。

我该怎么做?

最佳答案

您是正确的,因为您不能为此使用 UnmarshalerAttr。相反,ResultItem 可以实现 Unmarshaler这将允许您设置默认属性值:

package main
import (
    "encoding/xml"
    "fmt"
)

type ResultItem struct {
  Value string `xml:"value,attr"`
  Flag bool `xml:"flag,attr"`
}

func (ri *ResultItem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  type resultItem ResultItem // new type to prevent recursion
  item := resultItem{
    Flag: true,
  }
  if err := d.DecodeElement(&item, &start); err != nil {
    return err
  }
  *ri = (ResultItem)(item)
  return nil
}

func main() {
    var r struct {
      Item[] ResultItem `xml:"item"`
    }
    xml.Unmarshal([]byte(`
        <result x="ASDASD">
            <item value="1" flag="false" />
            <item value="2" flag="true" />
            <item value="3" />
        </result>`,
    ), &r)
    fmt.Printf("%+v\n", r)
}

关于xml - 去 XML 解析 : set missing attributes to "true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26956845/

相关文章:

java - 使用 text/plain 作为 XML over HTTP 的内容类型有哪些潜在问题?

java - 3 个 TextView 旁边的 Android 布局按钮

go - 如何向子进程发送信号?

sql - 谷歌 Go 和 SQLite : What library to use and how?

sql - 将 Xml 转换为表 SQL Server

javascript - Adobe InDesign JavaScript XML : How to add XML structure tags programmatically?

javascript - Google Geocoding API 挂起负载

go - 如何使用假客户端为 client-go 编写简单的测试?

go - 获取 go 模块问题

postgresql - 我应该如何在 Postgres 中存储 Go 的 time.Location?