首页  >  文章  >  后端开发  >  如何在 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