无法使用 Golang 中的反射将 xml 解组为动态创建的结构

Couldn't unmarshal xml to a dynamically created struct using reflection in Golang

这是我的解析代码xml。在函数的末尾,我应该在值切片中有结构字段的值。

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()
    }
}

但是,它出现恐慌并显示以下消息:

reflect.Value.Interface: cannot return value obtained from unexported field or method

我称之为:

utility.FindAttrs([]utility.Tag{
        {"name", reflect.String}, {"isUsed", reflect.String},
    }, errorChan)

我的 xml 是 <configuration name="mur" isUsed="mur"/>

需要创建一个指向结构的指针而不是一个值,并将指针的值(可以通过检索 Interface() 函数)传递给 Unmarshal 而不是它本身。

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()
    }