doukang1962 2010-01-05 22:11
浏览 167
已采纳

Go XML Unmarshal示例无法编译

The Xml example in the go docs is broken. Does anyone know how to make it work? When I compile it, the result is:

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

Here is the relevant code:

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条回答 默认 最新

  • dongzhui4927 2010-01-06 00:30
    关注

    The type Result is defined as:

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

    The type xml.Name, embedded in type Result, is defined as:

    // 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
    }
    

    Therefore, initialize, using composite literals, using something similar to one of:

    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条)

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件