1. 程式人生 > >go隨聊-xml讀取

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 ]