Go XML unmarshal array

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

Go XML unmarshal array

问题

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

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

使用以下代码:

// House struct used for houses xml file
type House struct {
    XMLName xml.Name `xml:"houses"`
    HouseID uint32 `xml:"houseid,attr"`
    Name    string `xml:"name,attr"`
    EntryX  uint16 `xml:"entryx,attr"`
    EntryY  uint16 `xml:"entryy,attr"`
    EntryZ  uint16 `xml:"entryz,attr"`
    Size    int    `xml:"size,attr"`
    TownID  uint32 `xml:"townid,attr"`
    Rent    int    `xml:"rent,attr"`
}

// LoadHouses parses the server map houses
func LoadHouses(file string, list []House) error {
    // Load houses file
    f, err := ioutil.ReadFile(file)

    if err != nil {
        return err
    }

    // Unmarshal houses file
    return xml.Unmarshal(f, &list)
}

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

英文:

I am trying to unmarshal a file that looks like this

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;houses&gt;
  &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;
&lt;/houses&gt;

With the following code

// House struct used for houses xml file
type House struct {
	XMLName xml.Name `xml:&quot;houses&quot;`
	HouseID uint32 `xml:&quot;houseid,attr&quot;`
	Name    string `xml:&quot;name,attr&quot;`
	EntryX  uint16 `xml:&quot;entryx,attr&quot;`
	EntryY  uint16 `xml:&quot;entryy,attr&quot;`
	EntryZ  uint16 `xml:&quot;entryz,attr&quot;`
	Size    int    `xml:&quot;size,attr&quot;`
	TownID  uint32 `xml:&quot;townid,attr&quot;`
	Rent    int    `xml:&quot;rent,attr&quot;`
}

// LoadHouses parses the server map houses
func LoadHouses(file string, list []House) error {
	// Load houses file
	f, err := ioutil.ReadFile(file)

	if err != nil {
		return err
	}

	// Unmarshal houses file
	return xml.Unmarshal(f, &amp;list)
}

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部分的定义。类似下面所示的内容,并对其进行解组。

type Houses struct {
    House    []House `xml:"house"`
}
英文:

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

type Houses struct {
	House    []House `xml:&quot;house&quot;`
}

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:

确定