本文實(shí)例講述了golang解析xml的方法。分享給大家供大家參考,具體如下:
golang解析xml真是好用,特別是struct屬性的tag讓程序簡(jiǎn)單了許多,其他變成語言需要特殊類型的在golang里直接使用tag舒服
xml文件點(diǎn)擊此處本站下載。
完整示例代碼:
復(fù)制代碼 代碼如下:
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)
}
希望本文所述對(duì)大家Go語言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- golang使用正則表達(dá)式解析網(wǎng)頁
- golang中interface接口的深度解析
- 利用Golang解析json數(shù)據(jù)的方法示例
- golang解析網(wǎng)頁利器goquery的使用方法
- golang解析域名的步驟全紀(jì)錄