gpt4 book ai didi

xml - Go:XML 解码嵌套结构到接口(interface){}

转载 作者:IT王子 更新时间:2023-10-29 01:42:54 26 4
gpt4 key购买 nike

我有 Python 背景,这是我第一次正式涉足 Go,所以我认为事情还没有进展顺利。

我目前正在使用 Go 实现 Affiliate Window XML API。该 API 遵循请求和响应的标准结构,因此为此我尽量保持干燥。信封总是有相同的结构,像这样:

<Envelope>
<Header></Header>
<Body></Body>
</Envelope>

HeaderBody 的内容将根据我请求的内容和响应而有所不同,因此我创建了一个基础 Envelope 结构

type Envelope struct {
XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
NS1 string `xml:"xmlns:ns1,attr"`
XSD string `xml:"xmlns:xsd,attr"`
Header interface{} `xml:"http://schemas.xmlsoap.org/soap/envelope/ Header"`
Body interface{} `xml:"Body"`
}

这很适合为请求编码 XML,但我在解码时遇到问题:

func NewResponseEnvelope(body interface{}) *Envelope {
envelope := NewEnvelope()
envelope.Header = &ResponseHeader{}
envelope.Body = body
return envelope
}

func main() {
responseBody := &GetMerchantListResponseBody{}
responseEnvelope := NewResponseEnvelope(responseBody)

b := bytes.NewBufferString(response)
xml.NewDecoder(b).Decode(responseEnvelope)
fmt.Println(responseEnvelope.Header.Quota) // Why can't I access this?
}

http://play.golang.org/p/v-MkfEyFPM可能用代码比用文字更好地描述问题:p

谢谢,

克里斯

最佳答案

Envelope 结构中的 Header 字段的类型是 interface{},它不是 struct 所以你不能引用它的任何字段。

为了引用名为 Quota 的字段,您必须使用包含 Quota 字段的静态类型声明 Header,例如像这样:

type HeaderStruct struct {
Quota string
}

type Envelope struct {
// other fields omitted
Header HeaderStruct
}

如果您不知道它将是什么类型或者您不能提交单一类型,您可以将其保留为interface{},但是您必须使用 Type switchesType assertion 在运行时将其转换为静态类型,后者看起来像这样:

headerStruct, ok := responseEnvelope.Header.(HeaderStruct)
// if ok is true, headerStruct is of type HeaderStruct
// else responseEnvelope.Header is not of type HeaderStruct

另一种选择是使用反射来访问 Envelope.Header 值的命名字段,但如果可能,请尝试以其他方式解决它。如果您有兴趣了解有关 Go 中反射的更多信息,我建议您先阅读 The Laws of Reflection 博文。

关于xml - Go:XML 解码嵌套结构到接口(interface){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28045510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com