首页  >  文章  >  后端开发  >  如何在 Golang 解组过程中捕获 XML 数组中的所有元素?

如何在 Golang 解组过程中捕获 XML 数组中的所有元素?

Patricia Arquette
Patricia Arquette原创
2024-10-24 06:16:02900浏览

How to Capture All Elements in an XML Array During Unmarshaling in Golang?

解组 XML 数组以捕获 Golang 中的所有元素

问题:

将 XML 数组解组为结构体时,仅检索数组的第一个元素。

原始代码:

<code class="go">type HostSystemIdentificationInfo []struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    var t HostSystemIdentificationInfo
    err := xml.Unmarshal(xmlBytes, &t)
    return t, err
}</code>

问题:

以上代码尝试将 XML 字符串解组为结构体 HostSystemIdentificationInfo 的切片,但它仅捕获数组的第一个元素。

解决方案:

捕获XML 数组,您需要使用 XML 解码器并多次调用其 Decode 方法。下面的代码演示了如何实现此目的:

<code class="go">// ... (same struct definitions as in the original code)

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    dec := xml.NewDecoder(bytes.NewReader(xmlBytes))
    var t HostSystemIdentificationInfo
    for {
        err := dec.Decode(&t)
        if err == io.EOF {
            break
        }
        if err != nil {
            return nil, err
        }
    }
    return t, nil
}</code>

说明:

  • xml.NewDecoder 函数创建一个从 io 读取的新 XML 解码器.Reader。
  • for 循环迭代 XML 输入,将每个元素解码到 t 切片中。
  • dec.Decode(&t) 方法将下一个 XML 元素解码到变量 t 中。
  • 循环一直持续到到达文件结尾(EOF),表示所有元素都已处理完毕。

用法:

<code class="go">xmlBytes = []byte(`
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
`)

t, err := unmarshal(xmlBytes)
if err != nil {
    log.Fatal(err)
}

fmt.Println(t) // All elements of the XML array will be printed</code>

以上是如何在 Golang 解组过程中捕获 XML 数组中的所有元素?的详细内容。更多信息请关注PHP中文网其他相关文章!

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