dream8877 2016-04-30 14:56
浏览 44
已采纳

在Go中将<tag value =“ val” />解组为Tag字符串

Say that I've got a Go struct defined as follows:

type MyType struct {
    FieldA string
    FieldB string
    FIeldC string
}

and XML that corresponds to it that looks like this:

<obj>
    <fieldA value="apple"/>
    <fieldB value="banana"/>
</obj>

where FieldA and FieldB are mandatory, and FieldC is optional. How do I specify the struct tags so as to get the field's value from the "value" attribute? This:

FieldA string `xml:"fieldA>value,attr"`
FieldB string `xml:"fieldB>value,attr"`
FieldC string `xml:"fieldC>value,attr,omitempty"`

generates "xml: fieldA>value chain not valid with attr flag" and this:

FieldA string `xml:"fieldA"`
FieldB string `xml:"fieldB"`
FieldC string `xml:"fieldC,omitempty"`

doesn't generate an error, but doesn't find the values of the fields.

  • 写回答

3条回答 默认 最新

  • dpii73380 2016-04-30 16:17
    关注

    To support both XML and JSON, you will have to define a simple type and implement the xml.Unmarshaler and xml.Marshaler interfaces on it, here's an example:

    type Field string
    
    func (f Field) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
        v := struct {
            Value string `xml:"value,attr"`
        }{string(f)}
        return e.EncodeElement(v, start)
    }
    
    func (f *Field) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
        var v struct {
            Value string `xml:"value,attr"`
        }
        err := d.DecodeElement(&v, &start)
        *f = Field(v.Value)
        return err
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题