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

标签 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"`
}

当我用值初始化它并用 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>

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

最佳答案

没有内容的 元素和 end-tag 之间的 XML 级别没有区别:

<soapenv:Header></soapenv:Header>

和一个 empty element tag :

<soapenv:Header/>

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


[为完整性添加]

...除了晦涩和过时的recommendation

For interoperability, the empty-element tag should be used, and should only be used, for elements which are declared EMPTY.

关于与 SGML 的互操作性:

for interoperability

[Definition: Marks a sentence describing a non-binding recommendation included to increase the chances that XML documents can be processed by the existing installed base of SGML processors which predate the WebSGML Adaptations Annex to ISO 8879.]

关于xml - 创建不带结束标记的 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57505477/

相关文章:

c++ - 使用 RapidXML 和 C++ 从 XML 文件构建树

sql-server - 在 T-SQL 中通过 XQuery 选择时连接 xml 值

go - 从 VSCode 下载 Golang 库时出错

postgresql - 通过其pq.StringArray属性查询GORM数据库

go - 如何在Golang中写入stdin?

java - 带有命名空间前缀的 TagSoup 属性

android - SAX 解析器不会读取和打印我的 xml 文件的一部分

javascript - 获取 HTML Body 中的 Javascript 变量

xml - Delphi XE 中的数据绑定(bind)向导 - 可以将其配置为映射到 MSXML 接口(interface)吗?

javascript - 如何使用部分属性名称选择 DOM 元素?