首页  >  文章  >  后端开发  >  如何避免在 Go 中仅解组 XML 数组的第一个元素?

如何避免在 Go 中仅解组 XML 数组的第一个元素?

Barbara Streisand
Barbara Streisand原创
2024-10-24 06:29:02532浏览

How to Avoid Unmarshaling Only the First Element of an XML Array in Go?

Go 中解组 XML 数组:仅获取第一个元素

XML 是企业环境中流行的一种数据格式,通常以复杂的形式表示,嵌套结构。 Go 是一种多功能编程语言,提供强大的 XML 解组功能。然而,了解解组 XML 数组的细微差别至关重要。

在特定场景中,开发人员在解组 XML 数组时遇到了问题。代码成功解组了第一个元素,但未能检索整个数组。

问题:

type HostSystemIdentificationInfo []struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func main() {
    var t HostSystemIdentificationInfo
    err := xml.Unmarshal([]byte(vv), &t)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(t)
}

const vv = `
  <HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
    <identifierValue>unknown</identifierValue>
    <identifierType>
      <label>Asset Tag</label>
      <summary>Asset tag of the system</summary>
      <key>AssetTag</key>
    </identifierType>
  </HostSystemIdentificationInfo>
`

预期输出:

[{ unknown {Asset Tag Asset tag of the system AssetTag}}]

实际输出:

[{ unknown {Asset Tag Asset tag of the system AssetTag}}]

解决方案:

问题的产生是由于对XML 解组过程。解组 XML 数组时,不能简单地提供目标结构作为接收数据的指针。相反,您必须创建一个 xml.Decoder 并重复调用其 Decode 方法。

package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "io"
    "log"
)

type HostSystemIdentificationInfo struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func main() {
    d := xml.NewDecoder(bytes.NewBufferString(vv))
    for {
        var t HostSystemIdentificationInfo
        err := d.Decode(&t)
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(t)
    }
}

const vv = `
  <HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
    <identifierValue>unknown</identifierValue>
    <identifierType>
      <label>Asset Tag</label>
      <summary>Asset tag of the system</summary>
      <key>AssetTag</key>
    </identifierType>
  </HostSystemIdentificationInfo>
`

通过利用 xml.Decoder,您可以正确地迭代 XML 数组中的每个元素并单独解组它们。

因此,通过遵循这些步骤,开发人员可以在 Go 中有效地解组 XML 数组,从而使他们能够高效地解析复杂的数据结构。

以上是如何避免在 Go 中仅解组 XML 数组的第一个元素?的详细内容。更多信息请关注PHP中文网其他相关文章!

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