go編程之XML檔案解析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

       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





       

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.