加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

go – encoding / xml处理未映射的元素

发布时间:2020-12-16 22:58:55 所属栏目:百科 来源:网络整理
导读:从 http://golang.org/pkg/encoding/xml/#Unmarshal起 If the XML element contains a sub-element that hasn’t matched any of the above rules and the struct has a field with tag “,any”, unmarshal maps the sub-element to that struct field. 我
从 http://golang.org/pkg/encoding/xml/#Unmarshal起

  • If the XML element contains a sub-element that hasn’t matched any of the above rules and the struct has a field with tag “,any”,
    unmarshal maps the sub-element to that struct field.

我无法将XML信封的剩余部分放入我的结构中(以显示我的映射不完整)

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

我知道你可以使用mgo包中的bson.M使用inline来完全使用这个方法 – 但看起来map [string] interface {}不是这里的答案.

编辑:
经过一些额外的游戏,我发现了我认为是一些额外的意外行为.

切换为[]字符串作为类型开始接受输入,但没有键/值对:http://play.golang.org/p/wCAJeeQa4m

我还计划调整encode / xml以解析html.我没有在文档中看到,如果一个元素存在多次,它将保存它的最后一个实例,而不是错误输出:http://play.golang.org/p/0MY__R-Xi3

解决方法

这里: http://play.golang.org/p/iY8YlxYym0

由于c是具体的东西,它不应该使用“,因此它应该有一个结构定义. C本身包含一个任意标签列表,因此它应该包含一个[]标签xml:’“,任何”……现在要捕获标签本身,你需要xml.Name来获取标签名称和“,” innerxml”.

最后结果如下:

const xmlString = `<foo><a>1</a><b>2</b><c><c1>3</c1><c2>4</c2></c></foo>`
type Foo struct {
    A int   `xml:"a"`
    B int   `xml:"b"`
    C Extra `xml:"c"`
}

type Extra struct {
    Items []Tag `xml:",any"`
}

type Tag struct {
    XMLName xml.Name
    Content string `xml:",innerxml"`
}

或者更短的版本:

type Foo struct {
    A int   `xml:"a"`
    B int   `xml:"b"`
    C struct {
        Items []struct {
            XMLName xml.Name
            Content string `xml:",innerxml"`
        } `xml:",any"`
    } `xml:"c"`
}

对于HTML,有go.net/html.对html使用xml解析器会很复杂.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读