2017-09-11 25 views
0
下面

見代碼: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" 
} 

對所有幫助非常感謝!

回答

0

由於v.SrcSrc是一個切片,其索引只顯示元素的順序,但不顯示其內部字段。如何解決一個任務:

  1. 製作特殊地圖指針元素

    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

  2. 使用XPath訪問具有特殊性能的元素,然後選擇喜歡//source[./id=1]/name