func main() {
file, err := os.Open(xmlFile)
if err != nil {
panic(err)
}
data, err := ioutil.ReadFile(file)
if err != nil {
panic(err)
}
defer file.Close()
NodeDecoder := xml.NewDecoder(bytes.NewBuffer(data))
var t xml.Token
for t,err = NodeDecoder.Token(); err = =nil; t,err = NodeDecoder.Token(){
switch token := t.(type){
case xml.StartElement:
name:= token.Name.Local
fmt.Println(name)
case xml.EndElement:
}
}
用了ioutil.ReadFile()来读取文件,就不必用os.Open()了,所以正确的写法是:
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
)
func main() {
// file, err := os.Open(xmlFile)
// if err != nil {
// panic(err)
// }
data, err := ioutil.ReadFile("vsproj.csproj")
if err != nil {
panic(err)
}
//defer file.Close()
NodeDecoder := xml.NewDecoder(bytes.NewBuffer(data))
var t xml.Token
for t, err = NodeDecoder.Token(); err == nil; t, err = NodeDecoder.Token() {
switch token := t.(type) {
case xml.StartElement:
name := token.Name.Local
fmt.Println(name)
case xml.EndElement:
}
}
}