首頁  >  文章  >  後端開發  >  如何在 Go 中使用屬性和浮點值解組 XML 元素?

如何在 Go 中使用屬性和浮點值解組 XML 元素?

DDD
DDD原創
2024-10-23 18:38:02823瀏覽

How to Unmarshal XML Elements with Attributes and Floating-Point Values in Go?

在Go 中使用屬性和浮點值解組XML 元素

使用屬性和屬性解組像所提供的XML 元素一個提供的XML 元素浮點數值,我們需要定義一個與XML 結構相對應的Go 結構體。

定義結構體

讓我們考慮一下中給出的兩個結構體定義問題:

第一個定義:

<code class="go">type ThingElem struct {
    Prop  int   `xml:"prop,attr"`
    Value float // ???
}

type ThingWrapper struct {
    T ThingElem `xml:"thing"`
}</code>

第二個定義:

<code class="go">type ThingElem struct {
    XMLName xml.Name `xml:"thing"` // Do I even need this?
    Prop    int      `xml:"prop,attr"`
    Value   float    // ???
}</code>

解決選項:

  • XMLName 屬性: XMLName 屬性通常應該用於指定結構的XML 元素名稱,因此在這種情況下我們不需要它,因為元素名稱在xml:"thing" 註解中明確指定。
  • 浮點值表示: 第一個結構中的 float 欄位無法正確解組,因為浮點值XML 中包含空格。我們需要在解組之前刪除這些空格。
  • 包裝器或直接嵌入:第二個結構定義使用包裝器 (ThingWrapper) 來表示 XML 元素。這是不必要的,因為 struct ThingElem 已經準確地表示了 XML 結構。

最終解決方案:

<code class="go">type Thing struct {
    Prop  int     `xml:"prop,attr"`
    Value float64 `xml:",chardata"`
}

type Root struct {
    Things []Thing `xml:"thing"`
}</code>

在此解決方案中,Thing 結構表示單一XML 元素,Root 結構體是一個容器,其中包含用於解組XML 根元素的Thing 結構體切片。

範例程式碼:

<code class="go">package main

import (
    "encoding/xml"
    "fmt"
)

const xmlData = `
<root>
<thing prop="1">1.23</thing>
<thing prop="2">4.56</thing>
</root>
`

func main() {
    root := &Root{}
    if err := xml.Unmarshal([]byte(xmlData), root); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(root.Things)
}</code>

此程式碼示範如何將 XML 元素解組為 Go 結構,包括從浮點數值中刪除空格。

以上是如何在 Go 中使用屬性和浮點值解組 XML 元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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