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 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致