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 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错