dshxbrzgi090608692 2018-06-12 08:04
浏览 344
已采纳

xml:已声明编码为“ utf-16”,但Decoder.CharsetReader为nil编组成功

I'm trying to unmarshal an XML feed containing German characters (e.g. ß, ä, Ö, ü, etc) into a struct, which results in the error: xml: encoding "utf-16" declared but Decoder.CharsetReader is nil unmarshal successful

Basically this is what I'm doing (omitted error checking for the parts that work):

resp, _ := http.Get(url)
defer resp.Body.Close()
bodyBytes, _ := ioutil.ReadAll(resp.Body)
err = xml.Unmarshal(bodyBytes, &target)
if err != nil {
  fmt.Println(err)
}

I've tried to convert xml to json using github.com/basgys/goxml2json, I've tried to convert to string and back to []byte before unmarshal, I've tried to use various decoders posted in other SO answers (since it say charset reader is nil), such as:

reader := bytes.NewReader(bodyBytes)
decoder := xml.NewDecoder(reader)
decoder.CharsetReader = charset.NewReader
err = decoder.Decode(&target)
if err != nil {
  fmt.Println(err)
}

No matter what I've tried it fails to unmarshal/decode the xml feed into the struct.. in some cases it ends up converting all the text to Chinese rather than German.

  • 写回答

1条回答 默认 最新

  • dongxie2756 2018-06-12 08:36
    关注

    If the charset.NewReader you're using in the second example is from https://godoc.org/golang.org/x/net/html/charset then the code shouldn't even compile since the CharsetReader field has a different signature from NewReader.


    To fix the error you can provide an "identical" charset reader, that is, one that returns the input unchanged.

    func identReader(encoding string, input io.Reader) (io.Reader, error) {
        return input, nil
    }
    
    // ...
    
    decoder.CharsetReader = identReader
    

    https://play.golang.org/p/BiU4T2qz1Z1


    NOTE: the above solution works for the example characters from the question but it may very well fail for other utf16 strings. In such a case a custom charset reader that can convert utf16 to utf8 should be provided instead of the identReader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备