首页 > 后端开发 > Golang > 正文

如何在 Go 中的 XML 解组过程中检索所有数组元素?

DDD
发布: 2024-10-24 00:16:01
原创
452 人浏览过

How to Retrieve All Array Elements During XML Unmarshaling in Go?

Go 中的 XML 数组解组:捕获所有元素

在提供的代码中,解组包含多个实例的 XML 字符串时会出现问题特定的结构类型。当前实现仅检索数组的第一个元素。

要克服此限制,请考虑以下方法:

使用 XML 解码器

利用 xml.Decoder 允许我们迭代 XML 数据并检索结构的所有实例。以下是更新后的代码:

<code class="go">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>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
    <identifierValue>Dell System</identifierValue>
    <identifierType>
        <label>OEM specific string</label>
        <summary>OEM specific string</summary>
        <key>OemSpecificString</key>
    </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
    <identifierValue>5[0000]</identifierValue>
    <identifierType>
        <label>OEM specific string</label>
        <summary>OEM specific string</summary>
        <key>OemSpecificString</key>
    </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
    <identifierValue>REDACTED</identifierValue>
    <identifierType>
        <label>Service tag</label>
        <summary>Service tag of the system</summary>
        <key>ServiceTag</key>
    </identifierType>
</HostSystemIdentificationInfo>`</code>
登录后复制

玩 Go:

[Playground 链接](http://play.golang.org/p/c7-E_Afe -3)

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

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!