创建不带结束标记的 XML 元素

Seb*_*n J 2 xml go xml-parsing

我有这个嵌套的 golang 结构:

// 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"`

// 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"`
}
Run Code Online (Sandbox Code Playgroud)

当我用值初始化它并编组它时,encoding/xml它看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

我如何去掉soapenv:Headerand的结束标签typ:Context,所以它看起来就像这样<soapenv:Header/>

kjh*_*hes 6

在 XML 级别上,没有内容的元素和结束标签之间没有区别:

<soapenv:Header></soapenv:Header>
Run Code Online (Sandbox Code Playgroud)

和一个空元素标签

<soapenv:Header/>
Run Code Online (Sandbox Code Playgroud)

要控制使用哪种表单,您必须将数据视为文本而不是 XML,但最好不要担心没有区别的差异。


[为了完整性而添加]

...除了晦涩且过时的建议之外

为了实现互操作性,应该使用空元素标签,并且应该仅用于声明为 EMPTY 的元素。

关于与 SGML 的互操作性:

为了互操作性

[定义:标记描述非约束性建议的句子,以增加现有 SGML 处理器安装基础处理 XML 文档的机会,该处理器早于 ISO 8879 的 WebSGML 适应附件。]