首頁  >  文章  >  後端開發  >  如何避免在 Go 中僅解組 XML 數組的第一個元素?

如何避免在 Go 中僅解組 XML 數組的第一個元素?

Barbara Streisand
Barbara Streisand原創
2024-10-24 06:29:02535瀏覽

How to Avoid Unmarshaling Only the First Element of an XML Array in Go?

Go 中解組XML 陣列:只取得第一個元素

XML 是企業環境中流行的資料格式,通常流行的資料格式以複雜的形式表示,嵌套結構。 Go 是一種多功能程式語言,提供強大的 XML 解組功能。然而,了解解組 XML 數組的細微差別至關重要。

在特定場景中,開發人員在解組 XML 陣列時遇到了問題。程式碼成功解組了第一個元素,但未能檢索整個陣列。

問題:

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() {
    var t HostSystemIdentificationInfo
    err := xml.Unmarshal([]byte(vv), &t)
    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>
`

預期輸出:

[{ unknown {Asset Tag Asset tag of the system AssetTag}}]

[{ unknown {Asset Tag Asset tag of the system AssetTag}}]

解:

問題的產生是由於對XML 解組過程。解組 XML 數組時,不能簡單地提供目標結構作為接收資料的指標。相反,您必須建立一個 xml.Decoder 並重複呼叫其 Decode 方法。

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>
`
透過利用 xml.Decoder,您可以正確地迭代 XML 陣列中的每個元素並單獨解組它們。

因此,透過遵循這些步驟,開發人員可以在 Go 中有效地解組 XML 數組,從而使他們能夠有效地解析複雜的資料結構。

以上是如何避免在 Go 中僅解組 XML 數組的第一個元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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