這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
XML儼然已經稱為我們程式開中一種資料交換和資訊傳遞不可缺少的一枚角色,當然任何語言對XML的解析支援都不可或缺,今天我們一起學習學習go的xml解析。
需要解析的XML檔案:student.xml
xml檔案內容:
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><students version="1"><student> <studentName>xixi</studentName> <studentId>3100561007</studentId></student><student> <studentName>xiaoq</studentName> <studentId>3100263101</studentId></student></students></span>
xml檔案包含學生實體資訊,xml版本,xml名字等資訊,我們需要做的就是通過go程式去取到這些資訊。
在go語言中我們進行xml解析用到的包為 encoding/xml,主要方法為
func Unmarshal(data []byte, v interface{}) error
引入需要使用的go標準庫 :
import ("encoding/xml""fmt""io/ioutil""os") 定義我們XML與記憶體映射的結構體來接受資料:(注意:結構體描述資訊中的欄位需要與xml中的一一對應,並且要區分大小寫,不然解析的時候會出錯)
type Student struct {XMLName xml.Name `xml:"student"`StudentName string `xml:"studentName"`StudentId string `xml:"studentId"`}type RecurlyStudents struct {XMLName xml.Name `xml:"students"`Version string `xml:"version,attr"`Stustruct []Student `xml:"student"`Description string `xml:",innerxml"`} 載入xml檔案,並讀取檔案資訊到data中:
<span style="white-space:pre"></span><pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" color:#c0c0c0;"> </span>fmt.Println(<span style=" color:#008000;">"------------xml</span><span style=" color:#c0c0c0;"> </span><span style=" color:#008000;">解析-----------"</span>)
file, err := os.Open("student.xml")
if err != nil {
fmt.Println("open xml file error")
return
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println("read file stream error")
return
}
解析xml檔案並輸出:
stus := RecurlyStudents{}err = xml.Unmarshal(data, &stus)if err != nil {fmt.Println("format xml data failed")return}fmt.Println("Description:" + stus.Description)fmt.Printf("XMLName:%v\n", stus.XMLName)fmt.Println("XMLVersion:" + stus.Version)for index, stu := range stus.Stustruct {fmt.Printf("the %d student,name:%s\n", index+1, stu.StudentName)fmt.Printf("the %d student,id:%s\n", index+1, stu.StudentId)}over