go解析讀取xml檔案
阿新 • • 發佈:2019-02-03
go語言解析XML
per.xml 準備被讀取的資料
<persons>
<person name="張三" age="20">
<gender>男</gender>
<interests>
<interest>程式設計</interest>
<interest>閱讀</interest>
</interests>
<salary>3500</salary >
</person>
</persons>
start.go
xml:”person”:xml中person欄位
xml:”name,attr”:xml中name屬性
注意:儲存欄位的變數名首字母必須是大寫
package main
import (
"io/ioutil"
"fmt"
"os"
"encoding/xml"
)
type Persons struct {
Person []Person `xml:"person"`
}
type Person struct {
Name string `xml:"name,attr"`
Age string `xml:"age,attr"`
Gender string `xml:"gender"`
Interests Interests `xml:"interests"`
}
type Interests struct {
Interest []string `xml:"interest"`
}
func main() {
//將檔案讀取成位元組陣列
content, err := ioutil.ReadFile("per.xml" )
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(9)
}
var ps Persons
//反序列化xml
xml.Unmarshal(content, &ps)
fmt.Println(ps.Person[0].Name)
fmt.Println(ps.Person[0].Age)
fmt.Println(ps.Person[0].Gender)
fmt.Println(ps.Person[0].Interests)
}
結果:
張三
20
男
{[程式設計 閱讀]}
注意:
當xml內部存放有大量資料時要考慮效能問題,上面程式碼是一次載入入記憶體