Xml namespace prefix issue at go

marshalling and unmarshalling are not working properly with xml namespace prefix

go version 1.9.2
See below code:

package main

import (

    "fmt"
    "encoding/xml")

type DeviceId struct {
    XMLName      xml.Name `xml:"DeviceId"`
    Manufacturer string   `xml:"Manufacturer"`
    OUI          string   `xml:"OUI"`
    ProductClass string   `xml:"ProductClass"`
    SerialNumber string   `xml:"SerialNumber"`
}

type CwmpInform struct {
    XMLName xml.Name `xml:"cwmp:Inform"`
    DeviceId     DeviceId      
}


func main() {
    rq := new(CwmpInform)
    data := `<cwmp:Inform>
                <DeviceId>
                <Manufacturer></Manufacturer>
                <OUI>48BF74</OUI>
                <ProductClass>FAP</ProductClass>
                <SerialNumber>1202000042177AP0008</SerialNumber>
                </DeviceId>
              </cwmp:Inform>`

    xml.Unmarshal([]byte (data), rq)
    fmt.Printf("Unmarshelled Content:%v", rq)
    output, err := xml.MarshalIndent(rq,"  ", "  ")
    if err != nil{
    fmt.Printf("error : %v", err)
    }
    fmt.Printf("Marshelled Content: %s\n", string(output))
}

I am getting empty structs as output.

The error returned by xml.Unmarshal is: expected element type <cwmp:Inform> but have <Inform>

This is a known issue. There might be a fix in Go 1.11.

Here’s a small hack to get your example working: https://play.golang.org/p/qCbsCoQ0cHc

2 Likes

Thanks a ton :slight_smile:
It worked! @nstratos

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.