问答详情
源自:5-2 获取所有节点名

语句不能实现

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:
        }
        
    }
    

提问者:qq_划胖_0 2016-09-03 19:35

个回答

  • 且听风吟_1
    2016-12-04 23:23:09

    用了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:
            }

        }
    }