go随聊-xml读取

XML的读取

假设本地xml文件config.xml

<?xml version="1.0" encoding="UTF-8"?>
<Message Version="1.0">
  <Item key="Channel" value="gin"/>
  <Item key="Filter" value="system,statistics,metric,facerecog,facesnap"/>
  <Item key="LogLevel" value="trace" desc="日志等级off,trace,debug,info,error,all"/>
  <Item key="ChannelHttpPort" value="9100" desc="http服务端口"/>
  <Item key="ConfigSSDB" value="192.168.10.25:18888" desc="ssdb地址"/>
  <Item key="ConfigRedis" value="192.168.10.25:6379" desc="redis地址"/>
</Message>

定义结构

type Item struct {
	XMLName xml.Name `xml:"Item"`
	Key     string   `xml:"key,attr"`
	Value   string   `xml:"value,attr"`
	Desc 	string	 `xml:"desc,attr"`
}

type Message struct {
	XMLName xml.Name `xml:"Message"`
	Svs     []Item   `xml:"Item"`
}

读取xml

var configItem map[string]string = make(map[string]string)
func loadXml(file string) {
	content, err := ioutil.ReadFile(file)
	if err != nil {
		return
	}

	var result Message
	err = xml.Unmarshal(content, &result)
	if err != nil {
		return
	}

	//将key-value值保持到map中
	configItem = make(map[string]string)
	for i := 0; i < len(result.Svs); i++ {
		configItem[result.Svs[i].Key] = result.Svs[i].Value
	}
}

例子

loadXml("G:\\xqplatform\\src\\xqplatform\\system.xml")
for k,v:=range configItem {
    fmt.Println("key[",k,"] value[",v,"]")
}
------------------------------------------------------
key[ ConfigSSDB ] value[ 192.168.10.25:18888 ]
key[ ConfigRedis ] value[ 192.168.10.25:6379 ]
key[ Channel ] value[ gin ]
key[ Filter ] value[ system,statistics,metric,facerecog,facesnap ]
key[ LogLevel ] value[ trace ]
key[ ChannelHttpPort ] value[ 9100 ]

猜你喜欢

转载自blog.csdn.net/yimin_tank/article/details/83547214