Golang: Unmarshalling XML with Dynamic Attributes
Introduction:
In Go, encoding/xml provides an efficient and versatile way to handle XML data. However, when dealing with XML elements that possess dynamic attributes, unmarshalling becomes challenging due to the unknown number and types of attributes present.
Question:
How can you unmarshal XML tags with dynamic attributes in Go when you do not anticipate the exact attributes that will be encountered?
Answer:
Prior to late 2017, this was not directly supported in Go's XML unmarshalling. However, with advancements in the encoding/xml package, this functionality has been implemented.
To unmarshal XML tags with dynamic attributes, you can use the following syntax:
type MyStruct struct { Attributes []xml.Attr `xml:",any,attr"` }
Here's an example to illustrate how it works:
package main import ( "encoding/xml" "fmt" ) func main() { type MyStruct struct { Attributes []xml.Attr `xml:",any,attr"` } data := `` var v MyStruct if err := xml.Unmarshal([]byte(data), &v); err != nil { panic(err) } fmt.Println(v.Attributes) }
In this example, the MyStruct type defines a field named Attributes. The xml:"...,any,attr" tag instructs the unmarshaller to assign any XML attributes to this field as xml.Attr slices.
When the unmarshaller encounters the XML data provided in the data variable, it successfully unmarshals the unknown attributes (ATTR1 and ATTR2) into the Attributes field of the v struct. This allows for dynamic handling of XML elements with varying attribute sets.
Note that this feature requires Go version 1.9 or later.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3