golang解析xml的方法

2019-11-10 10:37:12王旭

本文实例讲述了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("%#vn", v)
    // table
    for _, countryRegion := range v.CountryRegion {
        // fmt.Printf("%s,%sn", countryRegion.Code, countryRegion.Name)
        if len(countryRegion.State) == 0 {
            continue
        }
        for _, state := range countryRegion.State {
            // fmt.Printf("%s,%s,%sn", countryRegion.Code, state.Code, state.Name)
            if len(state.City) == 0 {
                continue
            }
            for _, city := range state.City {