Home >Backend Development >Golang >How to Create XML Elements without Closing Tags in Go?

How to Create XML Elements without Closing Tags in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 03:02:03519browse

How to Create XML Elements without Closing Tags in Go?

Create XML Element without Closing Tag in Go

In this scenario, you have a nested Go struct that represents an XML envelope with nested elements.

// TierRequest is the outer most XML envelope of soap request
type TierRequest struct {
    XMLName   xml.Name `xml:"soapenv:Envelope"`
    NsEnv     string   `xml:"xmlns:soapenv,attr"`
    NsType    string   `xml:"xmlns:typ,attr"`
    Header    string   `xml:"soapenv:Header"`
    Body      TierBody `xml:"soapenv:Body"`
}

// TierBody is an emtpy container with the GetCollectorProfile struct
type TierBody struct {
    GetCollectorProfiles GetCollectorProfile `Collectorxml:"typ:GetCollectorProfileRequest"`
}

// GetCollectorProfile struct has the context and collector number
type GetCollectorProfile struct {
    Contexts CollectorContext `xml:"typ:Context"`
    Number   int              `xml:"typ:CollectorNumber"`
}

// CollectorContext contanins a few variables as attributes
type CollectorContext struct {
    Channel  string `xml:"Channel,attr"`
    Source   string `xml:"Source,attr"`
    Language string `xml:"LanguageCode,attr"`
}

You marshal this struct to XML using encoding/xml, but you want to get rid of the closing tags for soapenv:Header and typ:Context to have empty element tags like <soapenv:Header/>.

There is no XML-level difference between these two forms, as an empty element tag is functionally equivalent to an end-tag for an element with no content. In other words, the content of the XML will be the same in either case:

<soapenv:Header></soapenv:Header>
<soapenv:Header/>

Therefore, it is not possible to control the use of empty element tags versus end-tags using standard XML techniques.

The above is the detailed content of How to Create XML Elements without Closing Tags in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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