0
下面
打印出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"
}
對所有幫助非常感謝!