Raggaer
Raggaer

Reputation: 3318

Go XML unmarshal array

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.

Upvotes: 1

Views: 1729

Answers (1)

miltonb
miltonb

Reputation: 7385

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"`
}

Upvotes: 1

Related Questions