doulin6448 2016-04-14 09:33
浏览 68

读取类型的属性XMLName属性值

Im working on my own MarshalXML function to get required output format for an input object, but cant seem to find a proper way of giving tags a proper names.

Let say i have:

type RootElement struct{
XMLName xml.Name `xml:"hello"`
world ChildElement `xml:"world"`
}

And a child element:

type ChildElement struct{
Value string
}

Then Encode method in MarshalXML for RootElement would give me:

<RootElement>
<ChildElement>
...
</ChildElement>
</RootElement>

Instead of that id have to create my own callset of EncodeToken methods in order to put there proper tag names, but even here i have to specify xml.Name as a constant string value even though i already have it defined in the model structs.

Is there some way to get 'hello' and 'world' tag names inside XMLMarshal?

  • 写回答

1条回答 默认 最新

  • donglu7998 2016-04-15 09:19
    关注

    I'm not sure why the RootElement name didn't work, but for the ChildElement, you have to put the tag xml:",chardata", so the Value is detected as the ChildElement's value and not a node.

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

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    type RootElement struct{
        XMLName xml.Name `xml:"hello"`
        World ChildElement `xml:"world",`
    }
    
    type ChildElement struct{
        Value string `xml:",chardata"`
    }
    
    func main() {
        r := RootElement{World: ChildElement{Value: "child value"}}
        m, err := xml.MarshalIndent(r, "", "  ")
        if err == nil {
            fmt.Printf("%s
    ", m)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数