前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang语言 xml解析实例

Golang语言 xml解析实例

作者头像
李海彬
发布2018-03-20 16:21:27
1.1K0
发布2018-03-20 16:21:27
举报
文章被收录于专栏:Golang语言社区Golang语言社区
代码语言:javascript
复制
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)
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-04-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档