Home > Backend Development > Golang > How to Dynamically Set XML Element Names in Go Structs?

How to Dynamically Set XML Element Names in Go Structs?

Susan Sarandon
Release: 2024-11-25 15:34:10
Original
614 people have browsed it

How to Dynamically Set XML Element Names in Go Structs?

Dynamically Defining XML Element Names in Go

Consider an XML file with two elements of identical structure, except for the element names. To represent these elements in Go, a struct with a dynamic element name is desired.

type Person struct {
    XMLName string `xml:"???` // How to make this dynamic?
    E1 string `xml:"ELEM1"`
    E2 string `xml:"ELEM2"`
    E3 string `xml:"ELEM3"`
    E4 string `xml:"ELEM4"`
}
Copy after login

The xml.Name type is introduced here. Its Local field allows for the dynamic setting of element names:

type Person struct {
    XMLName xml.Name
    E1 string `xml:"ELEM1"`
    // ...
}
Copy after login

At runtime, the element name can be assigned:

person := Person{
    XMLName: xml.Name{Local: "Person"},
    // ...
}
Copy after login

Note that the struct fields (E1 - E4) must be exported (start with uppercase letters) to be included in the XML output.

For a practical example, refer to the following playground:

http://play.golang.org/p/bzSutFF9Bo

The above is the detailed content of How to Dynamically Set XML Element Names in Go Structs?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template