首頁  >  文章  >  後端開發  >  如何將整個 XML 數組解組到 Go 結構中

如何將整個 XML 數組解組到 Go 結構中

Barbara Streisand
Barbara Streisand原創
2024-10-24 06:11:30341瀏覽

How to Unmarshal the Entire XML Array into a Go Struct

在 Go 中解組 XML 數組:檢索所有元素

將 XML 數組解組到 Go 結構體時,可以只檢索第一個元素。若要避免此問題並取得整個數組,請按照以下步驟操作:

使用多次迭代進行XML 解碼:

多個XML 實體駐留在XML 字符串中。要正確解組這些實體,需要 xml.Decoder。多次使用 d.Decode 來檢索每個單獨的實體。

示例代碼:

<code class="go">d := xml.NewDecoder(bytes.NewBufferString(VV))
for {
    var t HostSystemIdentificationInfo
    err := d.Decode(&t)
    if err == io.EOF { // End of file encountered
        break
    }
    if err != nil { // Handle any decoding errors
        log.Fatal(err)
    }
    fmt.Println(t) // Each element will be printed
}</code>

XML 示例:

<code class="xml"><HostSystemIdentificationInfo>
  <identifierValue>unknown</identifierValue>
  <identifierType>
    <label>Asset Tag</label>
    <summary>Asset tag of the system</summary>
    <key>AssetTag</key>
  </identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo>
  <identifierValue>Dell System</identifierValue>
  <identifierType>
    <label>OEM specific string</label>
    <summary>OEM specific string</summary>
    <key>OemSpecificString</key>
  </identifierType>
</HostSystemIdentificationInfo></code>

通過執行以下步驟,您可以成功將整個XML 陣列解組為Go 結構,確保您能如預期擷取所有元素。

以上是如何將整個 XML 數組解組到 Go 結構中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn