Golang解组变化结构索引来定义的值
问题描述:
下面
打印出v.Src [0]和v.Src [1]可以调出 “MYSOURCE” 和 “MySource2”。
但对比XML,项[0]和[1]不按ID在<id>x</id>
集我怎样才能做到这一点的解码器是使用<id>x</id>
为指标?
目标:v.Src [1]打印 “MYSOURCE”
这是我工作的代码
包主要
import (
"encoding/xml"
"fmt"
)
type Flow struct {
Id string `xml:"id"`
Name string `xml:"name"`
}
type Src struct {
Id string `xml:"id"`
Name string `xml:"name"`
Flows []Flow `xml:"flows>flow"`
}
type Result struct {
Src []Src `xml:"bar>sources>source"`
}
func main() {
data := `
<foo>
<bar>
<sources>
<source>
<id>1</id>
<name>MySource</name>
<flows>
<flow>
<id>1</id>
<name>MySource 1L</name>
</flow>
<flow>
<id>2</id>
<name>MySource 1R</name>
</flow>
</flows>
</source>
<source>
<id>2</id>
<name>MySource2</name>
<flows>
<flow>
<id>1</id>
<name>MySource2 2L</name>
</flow>
<flow>
<id>2</id>
<name>MySource2 2R</name>
</flow>
</flows>
</source>
</sources>
</bar>
</foo>`
v := Result{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v", v)
fmt.Printf("%#v", v.Src[0].Name) //Prints: "MySource"
fmt.Printf("%#v", v.Src[1].Name) //Prints: "MySource2"
}
对所有帮助非常感谢!
答
由于v.Src
与Src
是一个切片,其索引只显示元素的顺序,但不显示其内部字段。如何解决一个任务:
-
制作特殊地图指针元素
srcs := make(map[int64]*Src) for index, src := range v.Src { id, _ := strconv.ParseInt(src.Id, 10, 64) srcs[id] = &(v.Src[index]) } fmt.Printf("Srcs: %v\n", srcs) fmt.Printf("%#v\n", srcs[1].Name) //Prints: "MySource" fmt.Printf("%#v\n", srcs[2].Name) //Prints: "MySource2"
使用XPath访问具有特殊性能的元素,然后选择喜欢
//source[./id=1]/name