'XML Unmarshaling attribute & inner value

When attempting to parse some XML, in the below example.

How can the attribute 'id' for Owner be referenced and parsed?


import (
    "encoding/xml"
    "fmt"
)

var Sample = `<?xml version="1.0"?>                                                                                                                                                                      
<items>                                                                                                                                                                                     
  <item id="10">                                                                                                                                                                            
    <owner id="50">John Smith</owner>                                                                                                                                                       
    <name>Box</name>                                                                                                                                                                        
    <location>Kitchen</location>                                                                                                                                                            
  </item>                                                                                                                                                                                   
</items>`

type Item struct {
    XMLName  xml.Name `xml:"item"`
    Id       int      `xml:"id,attr"`
    Owner    string   `xml:"owner"`
    OwnerId  int      `xml:"owner,id,attr"`
    Name     string   `xml:"name"`
    Location string   `xml:"location"`
}

type Items struct {
    XMLName xml.Name `xml:"items"`
    Items   []Item   `xml:"item"`
}

func main() {
    items := Items{}
    data := []byte(Sample)
    xml.Unmarshal(data, &items)
    fmt.Println("items: ", items)
}


Solution 1:[1]

To reference the attribute 'id' for Owner: items.Items[0].Owner.Id

fmt.Println("Owner Id: ", items.Items[0].Owner.Id)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mads Hansen