[英]Couldn't unmarshal xml to a dynamically created struct using reflection in Golang
This is my code for parsing xml.这是我解析 xml 的代码。 At the end of the function, I should have values of fields of a struct in the values slice.在 function 的末尾,我应该在值切片中包含结构的字段值。
func FindAttrs(attrs []Tag, errorChan chan<- error) {
var tableFields []reflect.StructField
for _, v := range attrs {
tableFields = append(tableFields, reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.TypeOf(""),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
Offset: 0,
PkgPath: "utility",
Index: nil,
Anonymous: false,
})
}
unmarshalStruct := reflect.Zero(reflect.StructOf(tableFields))
err := xml.Unmarshal(ReadBytes(errorChan), &unmarshalStruct)
HandleError(err, "Error parse config", false, errorChan)
values := make([]interface{}, unmarshalStruct.NumField())
for i := 0; i < unmarshalStruct.NumField(); i++ {
values[i] = unmarshalStruct.Field(0).Interface()
}
}
But, it panics with the following message:但是,它会因以下消息而恐慌:
reflect.Value.Interface: cannot return value obtained from unexported field or method
I call it with:我称之为:
utility.FindAttrs([]utility.Tag{
{"name", reflect.String}, {"isUsed", reflect.String},
}, errorChan)
And my xml is <configuration name="mur" isUsed="mur"/>
而我的 xml 是<configuration name="mur" isUsed="mur"/>
Need to make a pointer to struct instead of a value and pass pointer's value, which can by retrieved Interface()
function, to Unmarshal instead of it itself.需要创建一个指向结构而不是值的指针并将指针的值传递给Interface()
而不是它本身。
var tableFields []reflect.StructField
for _, v := range attrs {
tableFields = append(tableFields, reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.TypeOf(""),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
})
}
rv := reflect.New(reflect.StructOf(tableFields)) // initialize a pointer to the struct
v := rv.Interface() // get the actual value
err := xml.Unmarshal([]byte(`<configuration name="foo" isUsed="bar"/>`), v)
if err != nil {
panic(err)
}
rv = rv.Elem() // dereference the pointer
values := make([]interface{}, rv.NumField())
for i := 0; i < rv.NumField(); i++ {
values[i] = rv.Field(i).Interface()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.