gpt4 book ai didi

xml - Golang 指定 xml 结构中的顶级标签

转载 作者:IT王子 更新时间:2023-10-29 01:42:29 24 4
gpt4 key购买 nike

所以我正在尝试将一些 xml 解码或解码为一个类型(我仍然不完全清楚区别是什么),而且我似乎无法指定最外层的类型(在本例中为 <people> ) .当我尝试指定此标记时,Marshalled 值没有包含任何我期望的内容,而不是出现错误。您如何指定最外层的标记,为什么第二个赋值没有预期的行为?

package main

import "fmt"
import "encoding/xml"
import "log"

var data string = `
<people>
<person>
<id>46</id>
<name>John Smith</name>
</person>
<person>
<id>3007</id>
<name>Joe Smith</name>
</person>
</people>
`

type Person struct {
Id int `xml:"id"`
Name string `xml:"name"`
}

type People struct {
PersonList []Person `xml:"person"`
}

type Response struct {
PeopleItem People `xml:"people"`
}

func main() {
// parsing People
// cannot specify outermost tag <people></people>
var people People
err := xml.Unmarshal([]byte(data), &people)

if err != nil {
log.Fatal(err)
}

fmt.Println(people)
// prints "{[{46 John Smith} {3007 Joe Smith}]}"
// which is reasonable

// attempting to parse entire response, yields struct of struct of empty slice
var response Response
err = xml.Unmarshal([]byte(data), &response)
if err != nil {
log.Fatal(err)
}

// response is struct of struct of empty array
// why does this happen?
fmt.Println(response)
// why does this print "{{[]}}" ?
}

最佳答案

您可以在不修改传入数据的情况下执行此操作,您可以使用特殊的 XMLName xml.Name 字段来设置外部标记,然后使用 xml:",chardata"访问它的内容。

这是一个例子:Try it on the go playground

package main

import (
"encoding/xml"
"fmt"
)

type simpleInt struct {
XMLName xml.Name `xml:"integer"`
Int int `xml:",chardata"`
}

type simpleString struct {
XMLName xml.Name `xml:"stringtag"`
String string `xml:",chardata"`
}

type simpleBoolean struct {
XMLName xml.Name `xml:"boolean"`
Boolean bool `xml:",chardata"`
}

func main() {

bint := []byte("<integer>1138</integer>")
bstring := []byte("<stringtag>Caimeo</stringtag>")
btrue := []byte("<boolean>true</boolean>")
bfalse := []byte("<boolean>false</boolean>")

i := simpleInt{}
xml.Unmarshal(bint, &i)
fmt.Println(i, i.Int)

s := simpleString{}
xml.Unmarshal(bstring, &s)
fmt.Println(s, s.String)

m := simpleBoolean{}
xml.Unmarshal(btrue, &m)
fmt.Println(m, m.Boolean)

xml.Unmarshal(bfalse, &m)
fmt.Println(m, m.Boolean)
}

关于xml - Golang 指定 xml 结构中的顶级标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403746/

24 4 0