3

go 文档中的 Xml 示例已损坏。有谁知道如何使它工作?当我编译它时,结果是:

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>gre@example.com</addr>
        </email>
        <email where='work'>
                <addr>gre@work.com</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 )
}
4

4 回答 4

4

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
}

因此,使用复合文字进行初始化,使用类似于以下之一的内容:

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}
于 2010-01-06T00:30:51.657 回答
3

线

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

需要成为

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

然后它应该按预期工作。我提交了一个补丁来修复文档,巧合的是不久之后发布了一个版本,所以没有人应该再次遇到这个特定问题。

于 2010-01-06T00:02:04.667 回答
1

如果您提供 xml.Name{} 以及其他参数,它也可以工作,如下所示:

var result = Result{ xml.Name{"", "result"}, "name", "phone", nil }
于 2010-01-06T00:19:51.463 回答
0

这里

var result Result

作品。

于 2010-08-22T00:39:30.313 回答