英文:
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
<?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>
With the following code
// 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)
}
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:"house"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论