加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Go学习笔记:xml库的使用

发布时间:2020-12-16 08:52:46 所属栏目:百科 来源:网络整理
导读:package mainimport ( "os" "io" "fmt" "encoding/xml" "strconv")type Config map[string]map[string]stringvar config = make(Config)type Class struct { XMLName xml.Name `xml:"class"` //xml元素名称 Id int `xml:"id,attr"` // Pers []Persion `xml:"


package main

import (
    "os"
    "io"
    "fmt"
    "encoding/xml"
    "strconv"
)

type Config map[string]map[string]string

var config = make(Config)

type Class struct {
    XMLName xml.Name  `xml:"class"`      //xml元素名称
    Id      int       `xml:"id,attr"`    //
    Pers    []Persion `xml:"persion"`    //
    Desc    string    `xml:",innerxml"`  //
}

type Persion struct {
    XMLName  xml.Name `xml:"persion"`
    Id       int      `xml:"id,attr"`
    Name     string   `xml:"name"`
    Age      int      `xml:"age"`
}

func (self *Config)LoadXmlFile(filename,node string) error{
    fd,err := os.Open(filename)
    if err != nil{
        return err 
    }   
    defer fd.Close()
    return self.Load(fd,node)
}
func (self *Config)Load(r io.Reader,node string) error {
    mynode := false
    if _,ok := (*self)[node]; !ok {
        (*self)[node] = make(map[string]string)
    }   
    decoder := xml.NewDecoder(r)
    for {
        token,err := decoder.Token()
        if err != nil {
            if err.Error() == "EOF" {
                break
            }
            return err
        }
        switch value := token.(type) {
            case xml.StartElement:
                switch {
                    case value.Name.Local == node:
                        mynode = true
                    case mynode == true:
                        tb,err := decoder.Token()
                        if err != nil {
                            continue
                        }
                        switch tv := tb.(type) {
                            case xml.CharData:
                                (*self)[node][value.Name.Local] = string(tv)
                        }
                }
            case xml.EndElement:
                if value.Name.Local == node{
                    mynode = false
                }
        }
    }
    return nil
}


func main(){
    var ps = make([]Persion,0)
    for i := 0; i < 5; i++ {
        var tp Persion
        tp.Id = i
        tp.Name = "persion" + strconv.Itoa(i)
        tp.Age = 20 + i
        ps = append(ps,tp)
    }
    var c = Class{Id:1,Pers: ps}
    var res,_ = xml.MarshalIndent(c,"","    ")
    fmt.Println(c)
    fmt.Println(string(res))
    config.LoadXmlFile("config.xml","global")
    fmt.Println(config)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读