xml - Go:将 XML 解码嵌套结构放入接口(interface){}中

标签 xml go struct interface

我有 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 的字段,您必须使用静态类型声明 Header,其中包含 Quota 字段,例如像这样:

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/

相关文章:

ios - 如何在 Swift 中将文件写入位于 Apple 文件应用程序的文件夹中

go - 使用 `go doc` 命令查看示例函数?

c++ - 使用模板删除/添加结构成员

代码在 Windows 中有效,但在 Linux 中无效!为什么? 【简单的指针问题】

c - 具有随机字符的随机长度字符串

Python LXML- 检查变量值是否具有非 ASCII 值的方法,如果是则返回 unicode 值

php - 使用 XPath 从 XML 获取标签名称

go - 如何将 []*type 传递给函数?

php - 直接在 PHP 中读取传递的 XML 文件

pointers - 防止在测试时更改结构指针值