[Golang] XML Parsing Example (2)
source link: http://siongui.github.io/2015/02/19/go-parse-xml-example-2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] XML Parsing Example (2)
Updated: February 21, 2015
following previous post [1], 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.
parse-2.go | repository | view raw
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:
[2][Golang] XML Parsing Example (2)
[3][Golang] XML Parsing Example (3)
[4][Golang] XML Parsing Example (4)
[5][Golang] XML Parsing Example (5) - Parse OPML
[6][Golang] XML Parsing Example (6) - Parse OPML Concisely
[7][Golang] XML Parsing Example (7) - Parse RSS 2.0
[8][Golang] XML Parsing Example (8) - Parse Atom 1.0
[9][Golang] Convert Atom to RSS
Author: Siong-Ui Te ∈ Category: Go
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK