encoding/xml处理未映射的元素

kwo*_*lfe 4 go

来自http://golang.org/pkg/encoding/xml/#Unmarshal

  • 如果XML元素包含未匹配任何上述规则的子元素,并且struct具有带有标记",any"的字段,则unmarshal将子元素映射到该struct字段.

我无法将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

Ego*_*gon 5

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

既然c是具体的东西,它不应该使用",any",因此它应该有一个结构定义.C本身包含一个任意标签列表,因此它应该包含一个[]Tag xml:'",any"'...现在要捕获它Tag自己,你需要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"`
}
Run Code Online (Sandbox Code Playgroud)

或者更短的版本:

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"`
}
Run Code Online (Sandbox Code Playgroud)

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