How Can I Marshal XML Elements with Dynamic Names in Go?

Barbara Streisand
Release: 2024-11-22 18:13:13
Original
603 people have browsed it

How Can I Marshal XML Elements with Dynamic Names in Go?

Marshaling XML Elements with Dynamic Names in Golang

The task of constructing XML documents from Go structures can pose challenges, especially when dealing with varying element names. The question arises: can we define a Go struct that allows for dynamic element names during the XML marshaling process?

XMLName and Dynamic Element Names

The Go documentation states that the XMLName field in a struct must be of type xml.Name, not a string. This struct contains two fields: "Space" and "Local." To set a dynamic element name, modify the "Local" field within the xml.Name type.

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

Example

In this example, we'll have a struct with the element name being "Person" or "Sender" based on the value stored in the XMLName.Local field.

import (
    "encoding/xml"
    "fmt"
)

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

func main() {
    person := Person{XMLName: xml.Name{Local: "Person"}, E1: "Value1"}
    sender := Person{XMLName: xml.Name{Local: "Sender"}, E1: "Value1"}

    // Marshal the struct into XML
    personXML, _ := xml.Marshal(person)
    senderXML, _ := xml.Marshal(sender)

    fmt.Println(string(personXML))
    fmt.Println(string(senderXML))
}
Copy after login

This example produces two distinct XML documents, one with the element name "Person" and the other with the element name "Sender."

Playground Example

For an interactive version of this example, visit the Go Playground: http://play.golang.org/p/bzSutFF9Bo

The above is the detailed content of How Can I Marshal XML Elements with Dynamic Names 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