Home > Backend Development > Golang > How Can I Marshal Dynamic XML Element Names in Go?

How Can I Marshal Dynamic XML Element Names in Go?

Mary-Kate Olsen
Release: 2024-11-26 17:23:09
Original
319 people have browsed it

How Can I Marshal Dynamic XML Element Names in Go?

Marshaling Dynamic XML Element Names in Golang

Problem

An XML file contains multiple elements with similar structures, but different names (e.g., PERSON and SENDER). The goal is to define a struct that allows for a dynamic element name.

Solution

While initially attempting to set the element name using the XMLName property wasn't successful, it is possible to achieve this by leveraging the following strategies:

  • Use the xml.Name type for XMLName: According to the documentation, the XMLName field requires the xml.Name type.
type Person struct {
    XMLName xml.Name
    E1 string `xml:"ELEM1"`
    // ...
}
Copy after login
  • Set the element name dynamically through xml.Name.Local: To assign a dynamic element name, use the Local field of xml.Name.
person := Person { 
    XMLName: xml.Name { Local: "Person" },
    // ...
}
Copy after login
  • Exported fields for XML inclusion: Ensure that the fields representing elements (e.g., E1 in this example) are exported by starting with an uppercase letter. This allows them to be included in the XML output.

Example

Refer to the following playground example for a complete implementation: http://play.golang.org/p/bzSutFF9Bo.

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