dongyun7897 2014-10-22 00:42
浏览 42
已采纳

与上下文无关的XML结构标记

I would like to be able to tag my struct without it needing to know what level it will be nested into an XML document. In other words, I want to be able to write:

type Elem struct {
    Datum string `xml:"datum"`
}

And have it work for both

<elem>
    <datum>Hello</datum>
</elem>

And

<list>
    <elem>
        <datum>Hello</datum>
    </elem>
</list>

However, in order for the latter example to work (when attempting to decode into a []Elem), I need to use the tag xml:"elem>datum", which decodes incorrectly for the first example. Is there a way for me to define an XML tag without knowing how the struct will be embedded? See here for a simple example:

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

  • 写回答

1条回答 默认 最新

  • dtihe8614 2014-10-22 02:17
    关注

    One way to solve this is through the use of an anonymous struct:

    func Test2_DecodeList() {
        xmlData := "<list><elem><datum>Hello</datum></elem></list>"
        var list struct {
            Elems []Elem `xml:"elem"`
        }
        if err := xml.Unmarshal([]byte(xmlData), &list); err != nil {
            fatal("Test2:", err)
        }
    
        if err := expectEq(1, len(list.Elems)); err != nil {
            fatal("Test2:", err)
        }
    
        if err := expectEq("Hello", list.Elems[0].Datum); err != nil {
            fatal("Test2:", err)
        }
    }
    

    Example: http://play.golang.org/p/UyYoyGgL_K

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题