How to Unmarshal XML Attributes with Unknown Attributes in Go?

DDD
Release: 2024-11-25 02:30:10
Original
136 people have browsed it

How to Unmarshal XML Attributes with Unknown Attributes in Go?

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)
}
Copy after login

When the above code is executed, it will print:

{
  Attributes: [
    {Name:ATTR1 Value:VALUE1}
    {Name:ATTR2 Value:VALUE2}
  ]
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template