How Can I Use Dynamic XML Element Names When Marshalling in Go?

Susan Sarandon
Release: 2024-11-27 02:45:14
Original
976 people have browsed it

How Can I Use Dynamic XML Element Names When Marshalling in Go?

Dynamic XML Element Names in Go Marshals

In Go, when marshalling XML, it is possible to specify custom tags for struct fields using the xml package. By default, the field name is used as the XML element name.

For cases where the element name needs to be dynamic, the XMLName field type has to be explicitly declared as xml.Name in the struct. The actual element name can then be set using the Local field of xml.Name.

Here's an example:

package main

import "encoding/xml"

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

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

In this example, the XML element name will be "Person" because we set XMLName.Local to "Person".

Note: Ensure that the fields to be included in the XML output are exported (start with an uppercase letter) in the struct definition.

The above is the detailed content of How Can I Use Dynamic XML Element Names When Marshalling 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template