Go学习笔记:xml库的使用

前端之家收集整理的这篇文章主要介绍了Go学习笔记:xml库的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


  1. package main
  2.  
  3. import (
  4. "os"
  5. "io"
  6. "fmt"
  7. "encoding/xml"
  8. "strconv"
  9. )
  10.  
  11. type Config map[string]map[string]string
  12.  
  13. var config = make(Config)
  14.  
  15. type Class struct {
  16. XMLName xml.Name `xml:"class"` //xml元素名称
  17. Id int `xml:"id,attr"` //
  18. Pers []Persion `xml:"persion"` //
  19. Desc string `xml:",innerxml"` //
  20. }
  21.  
  22. type Persion struct {
  23. XMLName xml.Name `xml:"persion"`
  24. Id int `xml:"id,attr"`
  25. Name string `xml:"name"`
  26. Age int `xml:"age"`
  27. }
  28.  
  29. func (self *Config)LoadXmlFile(filename,node string) error{
  30. fd,err := os.Open(filename)
  31. if err != nil{
  32. return err
  33. }
  34. defer fd.Close()
  35. return self.Load(fd,node)
  36. }
  37. func (self *Config)Load(r io.Reader,node string) error {
  38. mynode := false
  39. if _,ok := (*self)[node]; !ok {
  40. (*self)[node] = make(map[string]string)
  41. }
  42. decoder := xml.NewDecoder(r)
  43. for {
  44. token,err := decoder.Token()
  45. if err != nil {
  46. if err.Error() == "EOF" {
  47. break
  48. }
  49. return err
  50. }
  51. switch value := token.(type) {
  52. case xml.StartElement:
  53. switch {
  54. case value.Name.Local == node:
  55. mynode = true
  56. case mynode == true:
  57. tb,err := decoder.Token()
  58. if err != nil {
  59. continue
  60. }
  61. switch tv := tb.(type) {
  62. case xml.CharData:
  63. (*self)[node][value.Name.Local] = string(tv)
  64. }
  65. }
  66. case xml.EndElement:
  67. if value.Name.Local == node{
  68. mynode = false
  69. }
  70. }
  71. }
  72. return nil
  73. }
  74.  
  75.  
  76. func main(){
  77. var ps = make([]Persion,0)
  78. for i := 0; i < 5; i++ {
  79. var tp Persion
  80. tp.Id = i
  81. tp.Name = "persion" + strconv.Itoa(i)
  82. tp.Age = 20 + i
  83. ps = append(ps,tp)
  84. }
  85. var c = Class{Id:1,Pers: ps}
  86. var res,_ = xml.MarshalIndent(c,""," ")
  87. fmt.Println(c)
  88. fmt.Println(string(res))
  89. config.LoadXmlFile("config.xml","global")
  90. fmt.Println(config)
  91. }

猜你在找的XML相关文章