Creating XML Elements Without Closing Tags
Consider the following nested Go struct:
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"` // TierBody is an empty container with the GetCollectorProfile struct Body TierBody `Collectorxml:"typ:GetCollectorProfileRequest"` } type TierBody struct { GetCollectorProfiles GetCollectorProfile `Collectorxml:"typ:GetCollectorProfileRequest"` } type GetCollectorProfile struct { Contexts CollectorContext `xml:"typ:Context"` Number int `xml:"typ:CollectorNumber"` } type CollectorContext struct { Channel string `xml:"Channel,attr"` Source string `xml:"Source,attr"` Language string `xml:"LanguageCode,attr"` }
When initialized and marshaled using encoding/xml, it produces the following output:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http:/www.yahoo.com/tp/ets/2008/04/01/collector/types"> <soapenv:Header></soapenv:Header> <soapenv:Body> <GetCollectorProfiles> <typ:Context Channel="WEB" Source="WEB" LanguageCode="en-CA"></typ:Context> <typ:CollectorNumber>50000</typ:CollectorNumber> </GetCollectorProfiles> </soapenv:Body> </soapenv:Envelope>
Empty Element Tags vs. Elements with No Content
The distinction between an empty element tag (e.g.,
Choosing the Tag Form
To control which tag form is used, treat the data as text rather than XML. However, it is generally not necessary to worry about this distinction, as it has no practical implications.
Historical Note
An antiquated recommendation suggests that empty element tags be used solely for elements declared as EMPTY. However, this recommendation is primarily for interoperability with SGML and is not relevant for most modern XML applications.
The above is the detailed content of How do you create XML elements without closing tags in Go?. For more information, please follow other related articles on the PHP Chinese website!