dqw70970 2019-04-24 02:45
浏览 89
已采纳

XML Unmarshal base64字符串在Golang中构造

Currently, I'm implementing custom unmarshal xml for Bar which will unmarshal base64 string to Bar struct.

But when I run this program, it's stackoverflow like infinite recursive unmarshal my custom unmarshal.

GO Playground: https://play.golang.org/p/QD4IdxhZr1Q

package main

import (
    "bytes"
    "encoding/base64"
    "encoding/xml"
    "fmt"
)

type Foo struct {
    A Bar `xml:"a"`
}

type Bar struct {
    B string `xml:"b"`
    C string `xml:"c"`
    D string `xml:"d"`
}

func main() {
    var foo Foo
    // Input
    s := `<Foo><a>PGI+Yi10ZXN0PC9iPjxjPmMtdGVzdDwvYz48ZD5kLXRlc3Q8L2Q+Cg==</a></Foo>`

    err := xml.Unmarshal([]byte(s), &foo)

    if err != nil {
        panic(err)
    }

    fmt.Println("Foo:", foo)

}

func (m *Bar) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    var s string
    err := d.DecodeElement(&s, &start)

    fmt.Println("Decode Element:", s)

    if err != nil {
        return err
    }

    data, err := base64.StdEncoding.DecodeString(s)

    if err != nil {
        return err
    }

    fmt.Println("Base64 Decoded string:", string(data))

    var buf bytes.Buffer
    buf.WriteString("<Bar>")
    buf.WriteString(string(data))
    buf.WriteString("</Bar>")
    result := buf.String()
    fmt.Println("After add root node:", result)

    xml.Unmarshal([]byte(result), &m)

    return nil
}

Thank you!

  • 写回答

1条回答 默认 最新

  • dongma7796 2019-04-24 03:02
    关注

    https://play.golang.org/p/yZVtiEbugWH

    // define new type called BBar
    // same with bar
    type BBar Bar 
    xx := new(BBar)
    // the BBar doesn't have UnmarshalXML method
    xml.Unmarshal([]byte(result), xx)
    *m = Bar(*xx)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?