Go解析xml文件

demo.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
   <smtpServer>smtp.163.com</smtpServer>
   <smtpPort>25</smtpPort>
   <sender>user@163.com</sender>
   <senderPasswd>123456</senderPasswd>
   <receivers flag="true">
     <age>16</age>
     <user>Mike_Zhang@live.com</user>
     <user>test1@qq.com</user>
     <script>
     <![CDATA[
        function matchwo(a,b) {
            if (a < b && a < 0) then {
                return 1;
            } else {
                return 0;
            }
        }
        ]]>
     </script>
  </receivers>
 </config>

main.go

package main

import (
	"fmt"
	"io/ioutil"
	"encoding/xml"
)
/*
https://studygolang.com/static/pkgdoc/pkg/encoding_xml.htm
*/
// 定义结构体映射xml结构
type SConfig struct {
	XMLName  xml.Name `xml:"config"` // 指定最外层的标签为config
	SmtpServer string `xml:"smtpServer"` // 读取smtpServer配置项,并将结果保存到SmtpServer变量中
	SmtpPort int `xml:"smtpPort"`
	Sender string `xml:"sender"`
	SenderPasswd string `xml:"senderPasswd"`
	Receivers SReceivers `xml:"receivers"` // 读取receivers标签下的内容,以结构方式获取
  }
   
  type SReceivers struct {
	Age int `xml:"age"`
	Flag string `xml:"flag,attr"` // 读取flag属性
	User []string `xml:"user"` // 读取user数组
	Script string `xml:"script"` // 读取  数据
  }

func readXml(path string) {
	// 不用管理打开和关闭,ioutil 在内部已经处理过了
	data, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("读文件出错!", err)
		return
	}
	// fmt.Println(string(bytes))
	v := SConfig{}
	err = xml.Unmarshal(data, &v)
	if err != nil {
	  fmt.Printf("error: %v", err)
	  return
	}
   
	//fmt.Println(v)
	fmt.Println("SmtpServer : ",v.SmtpServer)
	fmt.Println("SmtpPort : ",v.SmtpPort)
	fmt.Println("Sender : ",v.Sender)
	fmt.Println("SenderPasswd : ",v.SenderPasswd)
	fmt.Println("Receivers.Flag : ",v.Receivers.Flag)
	fmt.Println("Receivers.Age : ",v.Receivers.Age)
	fmt.Println("Receivers.Script : ",v.Receivers.Script)
	for i,element := range v.Receivers.User {
	  fmt.Println(i,element)
	}
}

func main() {
	readXml("demo.xml")
}

输出:

SmtpServer :  smtp.163.com
SmtpPort :  25
Sender :  user@163.com
SenderPasswd :  123456
Receivers.Flag :  true
Receivers.Age :  16
Receivers.Script :

        function matchwo(a,b) {
            if (a < b && a < 0) then {
                return 1;
            } else {
                return 0;
            }
        }


0 Mike_Zhang@live.com
1 test1@qq.com

你可能感兴趣的:(Go语言,golang,xml,开发语言)