2017-09-11 6 views
0

を参照してくださいコード:Golangアンマーシャリング変化構造インデクス定義された値に

印刷アウトv.Src [0]とv.Srcは、[1] "MYSOURCE" と "MySource2" を起動します。

しかし、XMLを比較し、エントリ[0]と[1]私は、デコーダは、インデックスとして<id>x</id>を使用していることを達成することができますどのように

<id>x</id>の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" 
} 

感謝です!

答えて

0

Srcのスライスであるため、インデックスは要素の順序のみを示し、内部フィールドは表示しません。特定のプロパティを持つ要素にアクセスして、//source[./id=1]/name

のように選択するの要素

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" 

https://play.golang.org/p/6y3uW2jV13

  • XPathを使用へのポインタを持つ特殊なマップを作る

    1. :タスクを解決する方法

  • 関連する問題