golang作為一種編程語言,其在解析xml和json格式數據的時候擁有非常方便的庫函數,下面將分別講述如何使用這兩種工具。
解析xm
package main
import (
"encoding/xml"
"fmt"
)
type Website struct {
Name string `xml:"name,attr"`
Url string `xml:"url"`
Course []string `xml:"course"`
}
func main() {
xmlData := `www.google.com Golang Python Java `
var website Website
xml.Unmarshal([]byte(xmlData), &website)
fmt.Println(website)
}
解析json
package main
import (
"encoding/json"
"fmt"
)
type Website struct {
Name string `json:"name"`
Url string `json:"url"`
Course []string `json:"course"`
}
func main() {
jsonData := []byte(`
{
"name": "Google",
"url": "www.google.com",
"course": ["Golang", "Python", "Java"]
}`)
var website Website
json.Unmarshal(jsonData, &website)
fmt.Println(website)
}