xml - XML Unmarshal base64 字符串以在 Golang 中构造
问题描述
目前,我正在实现自定义 unmarshal xml,Bar
它会将 base64 字符串解组为Bar
结构。
但是当我运行这个程序时,它就像无限递归解组我的自定义解组一样的 stackoverflow。
去游乐场: 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
}
谢谢!
解决方案
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)
推荐阅读
- c# - 如何在c#中仅压缩路径中的文件和文件夹
- gulp - Gulp 4 php 与 browserSync
- javascript - 从 JavaScript 中的重定向事件获取 newURL
- python - 需要使用切片替换列表中的元素
- r - R中的MiKTeX - 我如何对齐结果方程
- php - Invoke-WebRequest 未将文件上传到服务器
- java - 如何在java反射中隐藏子模型类属性名称
- python - 从模块记录器记录到 sys.stdout
- node.js - 如何使“消息”和“频道”在一个 () 下可定义
- nginx - 如何找出为什么 Nginx 在将其用作 http/2 负载均衡器时返回 400?