当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang解析xml的方法

golang解析xml的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论
本文实例讲述了golang解析xml的方法。分享给大家供大家参考,具体如下: golang解析xml真是好用,特别是struct属性的tag让程序简单了许多,其他变成语言

本文实例讲述了golang解析xml的方法。分享给大家供大家参考,具体如下:

golang解析xml真是好用,特别是struct属性的tag让程序简单了许多,其他变成语言需要特殊类型的在golang里直接使用tag舒服

xml文件点击此处。

完整示例代码:

复制代码 代码如下:
package main
import (
    "os"
    "encoding/xml"
    // "encoding/json"
    "io/ioutil"
    "fmt"
)
type location struct {
    countryregion []countryregion
}
type countryregion struct {
    name string `xml:",attr"`
    code string `xml:",attr"`
    state []state
}
type state struct {
    name string `xml:",attr"`
    code string `xml:",attr"`
    city []city
}
type city struct {
    name string `xml:",attr"`
    code string `xml:",attr"`
    region []region
}
type region struct {
    name string `xml:",attr"`
    code string `xml:",attr"`
}
func main() {
    f, err := os.open("loclist.xml")
    if err != nil {
        panic(err)
    }
    data, err := ioutil.readall(f)
    if err != nil {
        panic(err)
    }
    // v := make(map[string]interface{})
    var v location
    err = xml.unmarshal(data, &v)
    if err != nil {
        panic(err)
    }
    // fmt.printf("%#v\n", v)
    // table
    for _, countryregion := range v.countryregion {
        // fmt.printf("%s,%s\n", countryregion.code, countryregion.name)
        if len(countryregion.state) == 0 {
            continue
        }
        for _, state := range countryregion.state {
            // fmt.printf("%s,%s,%s\n", countryregion.code, state.code, state.name)
            if len(state.city) == 0 {
                continue
            }
            for _, city := range state.city {
                // fmt.printf("%s,%s,%s,%s\n", countryregion.code, state.code, city.code, city.name)
                if len(city.region) == 0 {
                    continue
                }
                for _, region := range city.region {
                    fmt.printf("%s,%s,%s,%s,%s\n", countryregion.code, state.code, city.code, region.code, region.name)
                }
            }
        }
    }
    // // json
    // js, err := json.marshal(&v.countryregion[0])
    // if err != nil {
    //  panic(err)
    // }
    // fmt.printf("%s\n", js)
}

希望本文所述对大家go语言程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网