Go XML Unmarshal示例无法编译

时间:2010-01-05 22:11:50

标签: xml go

go docs中的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 个答案:

答案 0 :(得分:3)

该行

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

需要成为

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

然后它应该按预期工作。我提交了一个补丁来修复文档,巧合的是,很快就发布了一个版本,因此没有人会再遇到这个问题。

答案 1 :(得分:3)

type Result定义为:

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

嵌入type xml.Name的{​​{1}}定义为:

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
}

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

下面

var result Result

作品。