解析此xml时遇到了问题。

huangapple go评论86阅读模式
英文:

Having trouble unmarshaling this xml

问题

尝试理解如何在Go中解析XML。阅读了多个示例和stackoverflow问题。我想要的是一个包含系统上安装的所有补丁的切片。我甚至无法将补丁解析出来,没有错误,只是一个空的切片。可能是做了一些基本错误的事情,提前感谢任何建议。

<probe version="1.3" date="2012-03-26:17:10">
     <properties>
     </properties>
     <patches group="server">
        <file name="5002012-02-09CR00000server.jar"/>
        <file name="5002012-02-17CR00001server.jar"/>
     </patches>
     <patches group="client">
        <file name="5002012-02-09CR00000client.jar"/>
        <file name="5002012-02-17CR00001client.jar"/>
     </patches>
</probe>

type Patch struct {
    group string `xml:"group,attr"`
}

type Probe struct {
    XMLName xml.Name `xml:"probe"`
    Patches []Patch `xml:"patches"`
}
英文:

Trying to understand how to unmarshall XML in Go. Read through multiple examples and stackoverflow questions. What I want is a slice with the all the patches installed on the system. I can't even get the patches to unmarshal, no errors, just an empty slice. Probably doing something basically wrong, thanks in advance for any suggestions.

&lt;probe version=&quot;1.3&quot; date=&quot;2012-03-26:17:10&quot;&gt;
     &lt;properties&gt;
     &lt;/properties&gt;
     &lt;patches group=&quot;server&quot;&gt;
        &lt;file name=&quot;5002012-02-09CR00000server.jar&quot;/&gt;
        &lt;file name=&quot;5002012-02-17CR00001server.jar&quot;/&gt;
     &lt;/patches&gt;
     &lt;patches group=&quot;client&quot;&gt;
        &lt;file name=&quot;5002012-02-09CR00000client.jar&quot;/&gt;
        &lt;file name=&quot;5002012-02-17CR00001client.jar&quot;/&gt;
     &lt;/patches&gt;
&lt;/probe&gt;

<!-- language: lang-go -->

type Patch struct {
    group string `xml:&quot;group,attr&quot;`
}

type Probe struct {
    XMLName xml.Name `xml&quot;probe&quot;`
    Patches []Patch `xml:&quot;patches&quot;`
}

答案1

得分: 6

我相信你遇到的问题是xml包没有填充未导出的字段。xml文档中说:
>因为Unmarshal使用了reflect包,它只能赋值给导出的(大写字母开头)字段。

你只需要将group改为Group

type Patch struct { Group string `xml:&quot;group,attr&quot;` }

你可以在这里找到一个可工作的示例:
http://play.golang.org/p/koSzZr-Bdn

英文:

The problem I believe you have is the xml package not populating unexported fields. The xml documentation says:
>Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields.

All you need to do is to change group to Group:

type Patch struct { Group string `xml:&quot;group,attr&quot;` }

You have a working example here:
http://play.golang.org/p/koSzZr-Bdn

huangapple
  • 本文由 发表于 2012年11月16日 03:46:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/13404985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定