华域联盟 Golang golang解析xml的方法

golang解析xml的方法

本文实例讲述了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语言程序设计有所帮助。

本文由 华域联盟 原创撰写:华域联盟 » golang解析xml的方法

转载请保留出处和原文链接:https://www.cnhackhy.com/110124.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Ubuntu下安装Go语言开发环境及编辑器的相关配置

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们