2016-10-05 97 views
0

我試圖從波紋管XML的簡單XML的最後一個值,但輸出僅返回名稱的最後一個值Golang XML解組只返回子節點

package main 

import (
    "encoding/xml" 
    "fmt" 
) 

type Member struct { 
    Name []Names `xml:"names"` 
    Value string `xml:"value>string"` 
} 

type Names struct { 
    Name string `xml:"name"` 
} 

type Result struct { 

    Members []Member `xml:"params>param>value>array>data>value>struct>member"` 
} 

func main() { 
    data := ` 
    <methodResponse> 
    <params> 
     <param> 
      <value> 
       <array> 
        <data> 
         <value> 
          <string>12345abcde12345abcde12345</string> 
         </value> 
         <value> 
          <struct> 
           <member> 
            <names> 
            <name> 2 </name> 
            <name> 3 </name> 
            <name> 4 </name> 
            </names> 

            <value> 
             <string>trex</string> 
            </value> 
           </member> 

           <member> 
            <names> 
            <name> 2 </name> 
            <name> 3 </name> 
            <name> 4 </name> 
            </names> 

            <value> 
             <string>trex</string> 
            </value> 
           </member> 
          </struct> 
         </value> 
        </data> 
       </array> 
      </value> 
     </param> 
    </params> 
</methodResponse>` 

    v := Result{} 
    err := xml.Unmarshal([]byte(data), &v) 
    if err != nil { 
     fmt.Printf("error: %v", err) 
     return 
    } 
    fmt.Println(v) 
} 

回答

0

嘗試在The Go Playground

package main 

import (
    "encoding/xml" 
    "fmt" 
) 

type Member struct { 
    Names []string `xml:"names>name"` 
    Value string `xml:"value>string"` 
} 

type Result struct { 
    Members []Member `xml:"params>param>value>array>data>value>struct>member"` 
} 

func main() { 
    data := ` 
    <methodResponse> 
    <params> 
     <param> 
      <value> 
       <array> 
        <data> 
         <value> 
          <string>12345abcde12345abcde12345</string> 
         </value> 
         <value> 
          <struct> 
           <member> 
            <names> 
            <name> 2 </name> 
            <name> 3 </name> 
            <name> 4 </name> 
            </names> 

            <value> 
             <string>trex</string> 
            </value> 
           </member> 

           <member> 
            <names> 
            <name> 2 </name> 
            <name> 3 </name> 
            <name> 4 </name> 
            </names> 

            <value> 
             <string>trex</string> 
            </value> 
           </member> 
          </struct> 
         </value> 
        </data> 
       </array> 
      </value> 
     </param> 
    </params> 
</methodResponse>` 

    v := Result{} 
    err := xml.Unmarshal([]byte(data), &v) 
    if err != nil { 
     panic(err) 
    } 
    fmt.Println(v) 
} 

輸出:

{[{[ 2 3 4 ] trex} {[ 2 3 4 ] trex}]} 
+1

嘿,謝謝,這工作像一個魅力和簡單 – Chali

0

我想通了這一點,通過化妝名稱爲切片

名稱[]字符串xml:"name"