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/29884177/

相关文章:

golang 比较两个结构及其接口(interface)参数

java - 如何从 xml 文件中获取字符串形式的 URL?

xml - 可变嵌套 XML 数据的报告位置

c++ - Pugixml - 解析具有前缀映射和不带前缀映射的命名空间

xml - JAXB 能否首先通过包含进行编码,然后通过@XmlIDREF 进行编码以供后续引用?

go - 在 Golang 和 Rust 上使用 Messagepack 编码时的输出不同

c# - 在 C# 中使用 LINQ-To-XML 解析具有多个列表和类对象的 XML 数据

mysql - 将非常大的 XML 文件 (60GB) 导入 MySQL

javascript - jquery按属性值过滤xml数据

go - 在 golang 中,哪个更快地找到两个数组的交集?