xml 命名空间前缀问题

xml namespace prefix issue at go

使用 xml 命名空间前缀

编组和解组无法正常工作

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

上述程序的输出具有适当的编组内容和空编组内容:

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

但是当我将结构的 xml 标记从 xml:"cwmp:Inform" 更改为 xml:"cwmp Inform" 时,Unmarshelling 会正确发生,但我得到的 Marshelled 内容输出低于 :

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

我得到的不是 <cwmp:Inform>,而是 <Inform xmlns="cwmp">

这里可能是同样的问题

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

要解决这个问题,您需要使用两个结构,一个用于解组,第二个用于编组数据

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

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