Unmarshalling XML Attributes with Unknown Attributes in Go
In Go, the encoding/xml package allows us to marshal and unmarshal XML data into and from Go data structures. However, by default, it only supports unmarshalling XML tags with fixed attributes that are known beforehand.
Dynamic Attributes in XML
In some cases, XML documents may have tags with dynamic attributes that are not known in advance. This can pose a challenge when unmarshalling such XML data into Go structs.
Unmarshaling Dynamic Attributes
As of late 2017, Go supports unmarshalling XML tags with dynamic attributes using the xml:",any,attr" tag directive. This directive instructs the unmarshaler to collect all attributes into the xml.Attr slice.
Example:
package main import ( "encoding/xml" "fmt" ) func main() { var v struct { Attributes []xml.Attr `xml:",any,attr"` } data := `<TAG ATTR1="VALUE1" ATTR2="VALUE2" />` err := xml.Unmarshal([]byte(data), &v) if err != nil { panic(err) } fmt.Println(v) }
When the above code is executed, it will print:
{ Attributes: [ {Name:ATTR1 Value:VALUE1} {Name:ATTR2 Value:VALUE2} ] }
Note:
The xml:",any,attr" directive does not collect attributes from nested tags. If you need to collect attributes from nested tags, you will need to create a custom XML decoder.
The above is the detailed content of How to Unmarshal XML Attributes with Unknown Attributes in Go?. For more information, please follow other related articles on the PHP Chinese website!