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)
}
As of late 2017, this is supported by using:
var v struct {
    Attributes []xml.Attr `xml:",any,attr"`
}
Please see https://github.com/golang/go/issues/3633
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_
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With