doushi1957
2015-01-20 12:33
浏览 52

前往:将XML Unmarshal嵌套结构插入接口{}

I come from a Python background and this is my first proper foray into Go so I don't think things are clicking quite yet.

I'm currently implementing the Affiliate Window XML API in Go. The API follows a standard structure for Requests and Responses so to that end I'm trying to keep things dry. Envelopes always have the same structure, something like this:

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

The contents Header and Body will be different depending on what I'm requesting and the response so I created a base Envelope struct

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"`
}

This works well for marshaling the XML for a request but I'm having problems with unmarshaling:

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?
}

This http://play.golang.org/p/v-MkfEyFPM probably describes the problem better in code than I can in words :p

Thanks,

Chris

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题