Golang语言 xml解析实例

时间:2022-05-04
本文章向大家介绍Golang语言 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 {
                // fmt.Printf("%s,%s,%s,%sn", 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,%sn", 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("%sn", js)
}