dongxinm279890 2014-04-23 12:11
浏览 12
已采纳

Golang中缺少Xml标签

I am new to golang I am trying to make a xml in which i am using nested tags

For that my code is

type MyXml struct {
    XMLName xml.Name `xml:"myXml"`
    Id      int      `xml:"id,attr"`
    NewXml
}
type NewXml struct {
    XMLName xml.Name `xml:"newXml"`
    OneMoreXml
}

type OneMoreXml struct {
    Msg interface{} `xml:"oneMore"`
}

type Child struct {
    Param1 string `xml:"Param1"`
}

func main() {

    baseXml := &Child{Param1: "Param1"}
    retXml := GetXml(baseXml)
    fmt.Println("my xml is", retXml)

}
func MarshallXml(reqString interface{}) (newXml string) {
    xmlBody, err := xml.Marshal(reqString)
    if err != nil {
        fmt.Printf("error: %v
", err)
    }
    newXml = string(xmlBody)
    //fmt.Println(newXml)
    return
}
func GetXml(baseXml interface{}) (finalXml string) {

    startXml := new(MyXml)
    startXml.Id = 1
    startXml.Msg = baseXml
    finalXml = MarshallXml(startXml)
    return

}

but in my output xml Tag newXml is missing. I have tried it in various ways but some tag is always missing. I guess i am not understanding struct tag properly. So What i am doing wrong in above code and which basic concept of golang struct i am missing

  • 写回答

1条回答 默认 最新

  • dongtan5811 2014-04-23 13:11
    关注

    I had a look at the xml package doc and they say that "an anonymous struct field is handled as if the fields of its value were part of the outer struct". In your case, all fields thus get serialized as if they were part of MyXml.

    NewXml does not have any field (you just give it a name but there is nothing else) so nothing gets serialized for it. If you add a new field to it, you can see that it is serialized.

    type NewXml struct {
        XMLName xml.Name `xml:"newXml"`
        Test    int
        OneMoreXml
    }
    

    http://play.golang.org/p/vibSeQHTCr

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口