美文网首页GO
GO: 实例 t_xml.go

GO: 实例 t_xml.go

作者: 随风化作雨 | 来源:发表于2017-07-11 13:56 被阅读10次
    package main
    
    import (
        "encoding/xml"
        //"fmt"
        //"strings"
        "io/ioutil"
        "log"
    )
    
    type Result struct {
        Person []Person
    }
    
    type Person struct {
        Name      string
        Age       int
        Career    string
        Interests Interests
    }
    
    type Interests struct {
        Interest []string
    }
    
    func main() {
        content, err := ioutil.ReadFile("studygolang.xml")
        if err != nil {
            log.Fatal(err)
        }
        var result Result
        err = xml.Unmarshal(content, &result)
        if err != nil {
            log.Fatal(err)
        }
        log.Println(result)
    }
    
    /*
    func main() {
        var t xml.Token
        var err error
    
        input := `<Person><FirstName>Xu</FirstName><LastName>Xinhua</LastName></Person>`
        inputReader := strings.NewReader(input)
    
        // 从文件读取,如可以如下:
        // content, err := ioutil.ReadFile("studygolang.xml")
        // decoder := xml.NewDecoder(bytes.NewBuffer(content))
    
        decoder := xml.NewDecoder(inputReader)
    
        for t, err = decoder.Token(); err == nil; t, err = decoder.Token() {
            switch token := t.(type) {
            case xml.StartElement:
                name := token.Name.Local
                fmt.Printf("Token name: %s\n", name)
    
                for _, attr := range token.Attr {
                    attrName := attr.Name.Local
                    attrValue := attr.Value
                    fmt.Printf("An attribute is: %s %s\n", attrName, attrValue)
                }
            case xml.EndElement:
                fmt.Printf("Token of '%s' end\n", token.Name.Local)
            case xml.CharData:
                content := string([]byte(token))
                fmt.Printf("This is the content: %v\n", content)
            default:
                // ...
            }
        }
    }
    */
    

    相关文章

      网友评论

        本文标题:GO: 实例 t_xml.go

        本文链接:https://www.haomeiwen.com/subject/prfmhxtx.html