首页  >  文章  >  后端开发  >  如何将整个 XML 数组解组到 Go 结构中

如何将整个 XML 数组解组到 Go 结构中

Barbara Streisand
Barbara Streisand原创
2024-10-24 06:11:30341浏览

How to Unmarshal the Entire XML Array into a Go Struct

在 Go 中解组 XML 数组:检索所有元素

将 XML 数组解组到 Go 结构体时,可以仅检索第一个元素。要避免此问题并获取整个数组,请按照以下步骤操作:

使用多次迭代进行 XML 解码:

多个 XML 实体驻留在 XML 字符串中。要正确解组这些实体,需要 xml.Decoder。多次使用 d.Decode 来检索每个单独的实体。

示例代码:

<code class="go">d := xml.NewDecoder(bytes.NewBufferString(VV))
for {
    var t HostSystemIdentificationInfo
    err := d.Decode(&t)
    if err == io.EOF { // End of file encountered
        break
    }
    if err != nil { // Handle any decoding errors
        log.Fatal(err)
    }
    fmt.Println(t) // Each element will be printed
}</code>

XML 示例:

<code class="xml"><HostSystemIdentificationInfo>
  <identifierValue>unknown</identifierValue>
  <identifierType>
    <label>Asset Tag</label>
    <summary>Asset tag of the system</summary>
    <key>AssetTag</key>
  </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo>
  <identifierValue>Dell System</identifierValue>
  <identifierType>
    <label>OEM specific string</label>
    <summary>OEM specific string</summary>
    <key>OemSpecificString</key>
  </identifierType>
</HostSystemIdentificationInfo></code>

通过执行以下步骤,您可以成功将整个 XML 数组解组为 Go 结构,确保您按预期检索所有元素。

以上是如何将整个 XML 数组解组到 Go 结构中的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn