首頁 > 後端開發 > 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學習者快速成長!