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

如何在 Go 中使用屬性和值解組 XML?

Linda Hamilton
Linda Hamilton原創
2024-10-24 00:37:02277瀏覽

How to Unmarshal XML with Attributes and Values in Go?

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

XML 元素通常同時包含屬性和值。要成功將此類元素解組到 Golang 結構中,必須了解 XMLName 和「,chardata」註解的作用。

定義不含XMLName 的結構

考慮提供的XML:

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

沒有XMLName 欄位的對應結構可以是:

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

Prop 用xml 註解:"prop,attr" 表示它是事物元素。 Value 用 xml:",chardata" 註釋,指定它應該將元素的內容作為字串保存。

理解 XMLName

XMLName 可用來明確定義結構的 XML 標記名稱。在我們的例子中,XML 標籤名稱是推斷出來的,因為它與結構名稱 (ThingElem) 相符。因此,在此場景中不需要 XMLName。

使用包裝器結構

如果 XML 結構更複雜或可能不明確,您可以使用包裝器結構提供額外的背景資訊。例如,如果 XML 在根元素中包含多個 thing 元素:
<code class="xml"><root>
  <thing prop="1">
    1.23
  </thing>
  <thing prop="2">
    4.56
  </thing>
</root></code>

您將需要一個包裝器結構:
<code class="go">type ThingWrapper struct {
    T ThingElem `xml:"thing"`
}</code>

這裡,T 是表示thing 元素。

解組注意事項

對於提供的 XML 數據,您需要考慮元素值中的空格。由於 XML 預設不會保留空格,因此應修剪這些值,或可使用 xml:",innerxml" 註解。

結果結構可以如下解組:
<code class="go">package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

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(strings.TrimSpace(data)), thing)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(thing)
}</code>

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

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