2010-01-05 71 views
2

go docs中的Xml示例已損壞。有誰知道如何使它工作?當我編譯它,結果是:Go XML Unmarshal示例不編譯

xmlexample.go:34: cannot use "name" (type string) as type xml.Name in field value 
xmlexample.go:34: cannot use nil as type string in field value 
xmlexample.go:34: too few values in struct initializer 

下面是相關代碼:

package main 

import (
     "bytes" 
     "xml" 
) 

type Email struct { 
     Where string "attr"; 
     Addr string; 
} 

type Result struct { 
     XMLName xml.Name "result"; 
     Name string; 
     Phone string; 
     Email []Email; 
} 

var buf = bytes.NewBufferString (` 
<result> 
     <email where="home"> 
       <addr>[email protected]</addr> 
     </email> 
     <email where='work'> 
       <addr>[email protected]</addr> 
     </email> 
     <name>Grace R. Emlin</name> 
     <address>123 Main Street</address> 
</result>`) 


func main() { 
     var result = Result{ "name", "phone", nil } 
     xml.Unmarshal (buf , &result) 
     println (result.Name) 
} 

回答

3

type Result被定義爲:

type Result struct { 
    XMLName xml.Name "result" 
    Name string 
    Phone string 
    Email []Email 
} 

type xml.Name,嵌入type Result定義爲:

// A Name represents an XML name (Local) annotated 
// with a name space identifier (Space). 
// In tokens returned by Parser.Token, the Space identifier 
// is given as a canonical URL, not the short prefix used 
// in the document being parsed. 
type Name struct { 
    Space, Local string 
} 

因此,使用複合lite RALS,使用類似的東西一個:

var result = Result{xml.Name{}, "name", "phone", nil} 

var result = Result{xml.Name{"space", "local"}, "name", "phone", nil} 

var result = Result{Name: "name", Phone: "phone", Email: nil} 
3

var result = Result{ "name", "phone", nil } 

需求,成爲

var result = Result{ Name: "name", Phone: "phone", Email: nil } 

然後應該按預期工作。我提交了一個補丁來修復文檔,並且很快發佈了一個版本,所以沒有人應該再次遇到這個問題。

+0

感謝您發送補丁 – marketer 2010-01-07 20:14:35

1

,如果你與其他參數一起提供xml.Name {},像這樣它也適用:

var result = Result{ xml.Name{"", "result"}, "name", "phone", nil } 
0

這裏

var result Result 

作品。