following previous post , we add the attribute class="myClass" to the
div element in our sample XML:
            
              example-2.xml |
              repository |
              view raw
            
            |  | <?xml version="1.0" encoding="UTF-8"?><div class="myClass">Example</div>
 | 
  It is easy to read the attribute. Just add the following struct field in the
original struct:
Class string          `xml:"class,attr"`
"class,attr" means to read the attribute whose name is class.
Run code on Go Playground
            
              parse-2.go |
              repository |
              view raw
            
            |  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | package main
import (
	"io/ioutil"
	"encoding/xml"
	"fmt"
)
type div struct {
	XMLName	xml.Name	`xml:"div"`
	Class	string		`xml:"class,attr"`
	Content	string		`xml:",chardata"`
}
func main() {
	d := div{}
	xmlContent, _ := ioutil.ReadFile("example-2.xml")
	err := xml.Unmarshal(xmlContent, &d)
	if err != nil { panic(err) }
	fmt.Println("XMLName:", d.XMLName)
	fmt.Println("Class:", d.Class)
	fmt.Println("Content:", d.Content)
}
 | 
  
The output result:
XMLName: { div}
Class: myClass
Content: Example
Tested on: Ubuntu Linux 14.10, Go 1.4.
[Golang] XML Parsing Example series: