gpt4 book ai didi

使用包含 slice 的结构时 xml 恶作剧?

转载 作者:IT王子 更新时间:2023-10-29 02:17:21 29 4
gpt4 key购买 nike

我尝试了以下代码以了解为什么我在 golang 中遇到 xml 问题。

据我了解,我应该能够编码一个结构,然后将结果数据解编回相同类型的结构?

我期望的结果是一个包含子片的父结构,而不是子片为零?

playground link

package main

import (
"encoding/xml"
"fmt"
)

type Parent struct {
XMLName xml.Name `xml:"parent"`
Children []Child `xml:"children"`
}

type Child struct {
XMLName xml.Name `xml:"child"`
ID int `xml:"ID"`
}

func main() {
children := make([]Child, 3)

for i := range children {
children[i] = Child{ID: i}
}

p1 := Parent{Children: children}

data, err := xml.Marshal(p1)

if err != nil {
fmt.Printf("Error during marshal: %v\n", err)
}

fmt.Printf("Raw XML: %v\n", string(data))

p2 := Parent{}

err = xml.Unmarshal(data, &p2)

if err != nil {
fmt.Printf("Error during unmarshal: %v\n", err)
}

fmt.Printf("Unmarshalled struct: %v\n", p2)
}

最佳答案

它不是这样工作的:结构和 XML 之间没有特别的双射。

例如您生成以下 XML

<parent><child><ID>0</ID></child><child><ID>1</ID></child></parent>

因为你的 Child type 有一个字段 XMLName xml.Name带有 xml 标记“child”。这就是编码的工作原理。来自 http://tip.golang.org/pkg/encoding/xml/#Marshal

The name for the XML elements is taken from, in order of preference:

  • the tag on the XMLName field, if the data is a struct
  • the value of the XMLName field of type xml.Name
  • the tag of the struct field used to obtain the data
  • the name of the struct field used to obtain the data
  • the name of the marshalled type

现在看看如果你尝试解码它会发生什么:你的Parent类型标记其字段 Children []Child与“ child ”但是您的 XML 根本没有 <children>标签里面,只有<child> .

如果你使用

type Parent struct {
XMLName xml.Name `xml:"parent"`
Children []Child `xml:"child"` // "child", not "children"
}

它的工作方式如您所愿。

关于使用包含 slice 的结构时 xml 恶作剧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291161/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com