1. 程式人生 > >golang 操作XML配置文件

golang 操作XML配置文件

repl ase strings file ace else name 文件讀取 err

package main

import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"strings"
)

func main() {
header := `<?xml version=‘1.1‘ encoding=‘UTF-8‘?>`
var t xml.Token
var err error
//從文件讀取XML內容
content,err := ioutil.ReadFile("conf/build-app-conf.xml")
if err != nil {
fmt.Println(err)
}else {
//fmt.Println(bytes.NewBuffer(content))
confStr := strings.Replace(bytes.NewBuffer(content).String(),header,"",1)
decoder := xml.NewDecoder(bytes.NewBuffer([]byte(confStr)))
for t,err = decoder.Token(); err == nil; t,err = decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
name := token.Name.Local
fmt.Println(name)
case xml.EndElement:
fmt.Println(token.Name.Local)
case xml.CharData:
cont := string([]byte(token))
fmt.Println(cont)
default:
fmt.Println("ok")

}
}
}
}

golang 操作XML配置文件