首頁  >  文章  >  後端開發  >  我是否需要使用 XMLName 來解組具有屬性和浮點值的 XML 元素?

我是否需要使用 XMLName 來解組具有屬性和浮點值的 XML 元素?

Barbara Streisand
Barbara Streisand原創
2024-10-23 22:52:02729瀏覽

Do I Need to Use XMLName for Unmarshaling XML Elements with Attributes and Floating Point Values?

解組具有屬性和浮點值的XML 元素

要解組具有屬性和浮點值的XML 元素,您可以定義具有對應欄位的Go 結構體。但是,關於 xml.Name 屬性的使用有一些注意事項。

在提供的 XML 元素中:

<code class="xml"><thing prop="1">
  1.23
</thing></code>

ThingElem 結構應具有以下屬性:

  • Prop:此欄位對應屬性:
  • Prop:此欄位對應屬性。

Value:此欄位對應浮點值1.23。

選項 1:使用 XMLName

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

在此選項中,您可以為 ThingElem 結構新增 xml.Name 欄位。當 XML 結構不明確時通常使用此欄位。在這種情況下,這是不必要的,因為很明顯該結構對應於 thing 元素。

選項 2:不使用 XMLName

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

因為沒有歧義在 XML 結構中,您可以省略 xml.Name 欄位。

解組浮點值

要正確解組浮點數值,您需要確保 XML 中沒有空格。在您的範例中,該值為 1.23,但建議刪除空格並將其儲存為 1.23。

解組巢狀資料

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

您也可以透過以下方式解組巢狀資料定義一個包裝結構。例如,XML 包含多個事物元素。要解組它們,您需要定義一個ThingWrapper 結構:

完整程式碼範例

<code class="go">package main

import (
    "encoding/xml"
    "fmt"
)

type Root struct {
    Things []Thing `xml:"thing"`
}

type Thing struct {
    Prop  int     `xml:"prop,attr"`
    Value float64 `xml:",chardata"`
}

func main() {
    data := `<root><thing prop="1">1.23</thing><thing prop="2">4.56</thing></root>`
    thing := &Root{}
    err := xml.Unmarshal([]byte(data), thing)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(thing)
}</code>

以下是解組所提供的XML 資料的完整程式碼範例:

此程式碼將列印解析後的XML 數據,包括prop 屬性和浮點值。

以上是我是否需要使用 XMLName 來解組具有屬性和浮點值的 XML 元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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