本文介绍了Golang - 解组额外的XML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以用动态属性解组XML标签(我不知道每次我会得到哪些属性)。

也许它还不被支持。请参阅



类似于:

 包主

import(
encoding / xml
fmt


func main(){
var v struct {
属性[] xml.Attr`xml:,任何`
}

data:=`< TAG ATTR1 =VALUE1ATTR2 =VALUE2/>`

err:= xml.Unmarshal([] byte(data),& v)
if err!= nil {
panic(err)
}
fmt.Println(v)
}


解决方案

您需要实现您自己的

  package main 

import(
encoding / xml
fmt


类型CustomTag结构{
名称字符串
属性[] xml。 Attr


func(c * CustomTag)UnmarshalXML(d * xml.Decoder,start xml.StartElement)错误{
c.Name = start.Name.Local
c.Attributes = start.Attr
return d.Skip()
}

func main(){
v:=& CustomTag {}

data:= [] byte('< tag ATTR1 =VALUE1ATTR2 =VALUE2/>`)

err:= xml.Unmarshal(data,& amp ; v)如果err!= nil {
panic(err)
}
fmt.Printf(%+ v \ n,v)
}

输出

 & {Name:tag属性:[{Name:{Space:Local:ATTR1} Value:VALUE1} {Name:{Space:Local:ATTR2} Value:VALUE2}]} 


Is there a way to unmarshal XML tags with dynamic attributes (I don't know which attributes I'll get every time).

Maybe it's not supported yet. See Issue 3633: encoding/xml: support for collecting all attributes

Something like :

package main

import (
    "encoding/xml"
    "fmt"
)

func main() {
    var v struct {
        Attributes []xml.Attr `xml:",any"`
    }

    data := `<TAG ATTR1="VALUE1" ATTR2="VALUE2" />`

    err := xml.Unmarshal([]byte(data), &v)
    if err != nil {
        panic(err)
    }
    fmt.Println(v)
}
解决方案

You need to implement your own XMLUnmarshaler

package main

import (
    "encoding/xml"
    "fmt"
)

type CustomTag struct {
    Name       string
    Attributes []xml.Attr
}

func (c *CustomTag) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    c.Name = start.Name.Local
    c.Attributes = start.Attr
    return d.Skip()
}

func main() {
    v := &CustomTag{}

    data := []byte(`<tag ATTR1="VALUE1" ATTR2="VALUE2" />`)

    err := xml.Unmarshal(data, &v)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", v)
}

outputs

&{Name:tag Attributes:[{Name:{Space: Local:ATTR1} Value:VALUE1} {Name:{Space: Local:ATTR2} Value:VALUE2}]}

http://play.golang.org/p/9ZrpIT32o_

这篇关于Golang - 解组额外的XML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 08:04