首頁  >  文章  >  後端開發  >  如何在 Golang 解組過程中擷取 XML 陣列中的所有元素?

如何在 Golang 解組過程中擷取 XML 陣列中的所有元素?

Patricia Arquette
Patricia Arquette原創
2024-10-24 06:16:02900瀏覽

How to Capture All Elements in an XML Array During Unmarshaling in Golang?

解組XML 數組以捕獲Golang 中的所有元素

問題:

將XML 數組解組體時,僅檢索數組的第一個元素。

原始程式碼:

<code class="go">type HostSystemIdentificationInfo []struct {
    IdentiferValue string `xml:"identifierValue"`
    IdentiferType  struct {
        Label   string `xml:"label"`
        Summary string `xml:"summary"`
        Key     string `xml:"key"`
    } `xml:"identifierType"`
}

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    var t HostSystemIdentificationInfo
    err := xml.Unmarshal(xmlBytes, &t)
    return t, err
}</code>

問題:

以上程式碼嘗試將XML 字串解組為結構體HostSystemIdentificationInfo 的切片,但它只捕獲數組的第一個元素。

解決方案:

捕獲XML 數組,您需要使用 XML 解碼器並多次呼叫其 Decode 方法。下面的程式碼示範如何實現此目的:

<code class="go">// ... (same struct definitions as in the original code)

func unmarshal(xmlBytes []byte) (HostSystemIdentificationInfo, error) {
    dec := xml.NewDecoder(bytes.NewReader(xmlBytes))
    var t HostSystemIdentificationInfo
    for {
        err := dec.Decode(&t)
        if err == io.EOF {
            break
        }
        if err != nil {
            return nil, err
        }
    }
    return t, nil
}</code>

說明:

  • xml.NewDecoder 函數建立一個從io 讀取的新XML 解碼器.Reader。
  • for 迴圈迭代 XML 輸入,將每個元素解碼到 t 切片中。
  • dec.Decode(&t) 方法將下一個 XML 元素解碼到變數 t 中。
  • 循環一直持續到到達檔案結尾(EOF),表示所有元素都已處理完畢。

用法:

<code class="go">xmlBytes = []byte(`
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
<HostSystemIdentificationInfo xsi:type="HostSystemIdentificationInfo">
  <identifierValue>...</identifierValue>
  <identifierType>...</identifierType>
</HostSystemIdentificationInfo>
`)

t, err := unmarshal(xmlBytes)
if err != nil {
    log.Fatal(err)
}

fmt.Println(t) // All elements of the XML array will be printed</code>

以上是如何在 Golang 解組過程中擷取 XML 陣列中的所有元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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