xmlgoxml-namespaces

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

Output of above program with proper marshalled Content and empty Marshelled content :

Unmarshelled Content:&{{ } {{ }    }}
 Marshelled Content: 
  <cwmp:Inform>
    <DeviceId>
      <Manufacturer></Manufacturer>
      <OUI></OUI>
      <ProductClass></ProductClass>
      <SerialNumber></SerialNumber>
    </DeviceId>
  </cwmp:Inform>

but when i change the struct's xml tag from xml:"cwmp:Inform" to xml:"cwmp Inform", then Unmarshelling happens properly, but i get below output for Marshelled content :

<Inform xmlns="cwmp">
    <DeviceId>
      <Manufacturer></Manufacturer>
      <OUI>48BF74</OUI>
      <ProductClass>FAP</ProductClass>
      <SerialNumber>1202000042177AP0008</SerialNumber>
    </DeviceId>
  </Inform>

Instead of getting <cwmp:Inform>, I am getting <Inform xmlns="cwmp">


Solution

  • Is probably the same issue here

    https://github.com/golang/go/issues/9519

    To fix that you need to use two structs, one for Unmarshalling and second to Marshalling data

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