Golang——解析GBK编码XML文件

Golang——解析GBK编码XML文件

对于golang的xml解析,大家应该很熟悉了,或者说golang的xml解析其实很简单。语言本身支持xml解析,通过实例即可快速理解。但是在实际开发中总会遇到各种问题,比如xml的encoding是GBK的,导致解析失败!!原因是Golang 默认不支持 UTF-8 以外的字符集 。

解决方法

使用golang.org/x/net/html/charset库

步骤1、安装golang.org/x/net/html/charset

如果你已经?直接

go get golang.org/x/net/html/charset

如果没有?则进行步骤:

1. 在你的GOPATH下新建目录:golang.org/x
2. 进入到x目录下,在该目录打开cmd执行命令:git clone https://github.com/golang/net.git
  • 注意,如果缺少其他glang下的包,也是可以在github上找到的。地址:https://github.com/golang

步骤2、编码转换

func init() {
    type resRoot struct {
        XMLName    xml.Name `xml:"resRoot"`
        GuoduCount string   `xml:"rcode"`
    }

    data := `
     xml version="1.0" encoding="GBK"?>
        
            59529
        
    `
    decoder := xml.NewDecoder(bytes.NewReader([]byte(data)))
    decoder.CharsetReader = func(c string, i io.Reader) (io.Reader, error) {
        return charset.NewReaderLabel(c, i)
    }
    result := &resRoot{}
    decoder.Decode(result)
    fmt.Println(result)
}

你可能感兴趣的:(Golang)