Go XML unmarshal array

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

Go XML unmarshal array

问题

我正在尝试解析一个看起来像这样的文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <houses>
  3. <house name="Rhyves Flats 14" houseid="1" entryx="167" entryy="361" entryz="6" rent="0" townid="2" size="17" />
  4. </houses>

使用以下代码:

  1. // House struct used for houses xml file
  2. type House struct {
  3. XMLName xml.Name `xml:"houses"`
  4. HouseID uint32 `xml:"houseid,attr"`
  5. Name string `xml:"name,attr"`
  6. EntryX uint16 `xml:"entryx,attr"`
  7. EntryY uint16 `xml:"entryy,attr"`
  8. EntryZ uint16 `xml:"entryz,attr"`
  9. Size int `xml:"size,attr"`
  10. TownID uint32 `xml:"townid,attr"`
  11. Rent int `xml:"rent,attr"`
  12. }
  13. // LoadHouses parses the server map houses
  14. func LoadHouses(file string, list []House) error {
  15. // Load houses file
  16. f, err := ioutil.ReadFile(file)
  17. if err != nil {
  18. return err
  19. }
  20. // Unmarshal houses file
  21. return xml.Unmarshal(f, &list)
  22. }

这没有返回任何错误。但是房屋切片是空的。一切似乎都正确,属性也被设置了,XMLName也是正确的。

英文:

I am trying to unmarshal a file that looks like this

  1. &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
  2. &lt;houses&gt;
  3. &lt;house name=&quot;Rhyves Flats 14&quot; houseid=&quot;1&quot; entryx=&quot;167&quot; entryy=&quot;361&quot; entryz=&quot;6&quot; rent=&quot;0&quot; townid=&quot;2&quot; size=&quot;17&quot; /&gt;
  4. &lt;/houses&gt;

With the following code

  1. // House struct used for houses xml file
  2. type House struct {
  3. XMLName xml.Name `xml:&quot;houses&quot;`
  4. HouseID uint32 `xml:&quot;houseid,attr&quot;`
  5. Name string `xml:&quot;name,attr&quot;`
  6. EntryX uint16 `xml:&quot;entryx,attr&quot;`
  7. EntryY uint16 `xml:&quot;entryy,attr&quot;`
  8. EntryZ uint16 `xml:&quot;entryz,attr&quot;`
  9. Size int `xml:&quot;size,attr&quot;`
  10. TownID uint32 `xml:&quot;townid,attr&quot;`
  11. Rent int `xml:&quot;rent,attr&quot;`
  12. }
  13. // LoadHouses parses the server map houses
  14. func LoadHouses(file string, list []House) error {
  15. // Load houses file
  16. f, err := ioutil.ReadFile(file)
  17. if err != nil {
  18. return err
  19. }
  20. // Unmarshal houses file
  21. return xml.Unmarshal(f, &amp;list)
  22. }

This is not returning any error. But the house slice is empty. Everything seems correct, the attrs are set and the XMLName too.

答案1

得分: 1

你的代码缺少对XML中Houses部分的定义。类似下面所示的内容,并对其进行解组。

  1. type Houses struct {
  2. House []House `xml:"house"`
  3. }
英文:

Your code is missing a definition of the Houses part of the XML. Something like what is shown below and unmarshal on that.

  1. type Houses struct {
  2. House []House `xml:&quot;house&quot;`
  3. }

huangapple
  • 本文由 发表于 2017年1月4日 08:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41454603.html
匿名

发表评论

匿名网友

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

确定