」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中的 XML 解組過程中檢索所有數組元素?

如何在 Go 中的 XML 解組過程中檢索所有數組元素?

發佈於2024-11-11
瀏覽:783

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

Go 中的XML 數組解組:捕獲所有元素

在提供的程式碼中,在解組包含多個實例的XML字串時會出現問題特定的結構類型。目前實作僅檢索數組的第一個元素。

要克服此限制,請考慮以下方法:

使用XML 解碼器

利用xml.Decoder 讓我們迭代XML 資料並檢索該結構的所有實例。這是更新後的程式碼:

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>`

玩Go:

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

版本聲明 本文轉載於:1729694416如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3