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 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发