Go的xml.Marshal返回无效字符。

huangapple go评论66阅读模式
英文:

Go xml.Marshal returns invalid characters

问题

我使用下面的代码生成字符串 str 的 XML 编码:

str := string([]byte{0x01})
marshalBytes, _ := xml.Marshal(str)
fmt.Println(string(marshalBytes)) // 输出: <string>�</string>; � 在字节中表示为 [239 191 189]。

显然,� 并不等同于 0x01。

我该如何修复这个问题?

英文:

I use the code below generate a XML encoding of string str:

str := string([]byte{0x01})
marshalBytes, _ := xml.Marshal(str)
fmt.Println(string(marshalBytes)) // output: <string>�</string>; � is [239 191 189] in bytes.

Obviously, � is not equivalent of 0x01.

How can I fix it?

答案1

得分: 5

字节[239 191 189]是Unicode替换字符的UTF-8编码。

XML编组器将字节0x1替换为Unicode替换字符,因为字节0x01在XML中不是合法字符

无法阻止XML编组器使用替换字符。

英文:

The bytes [239 191 189] are the UTF-8 encoding of the Unicode Replacement Character.

The XML marshaler replaces the byte 0x1 with the Unicode Replacement Character because
the byte 0x01 is not a legal character in XML.

It is not possible to prevent the XML marshaler from using the replacement.

huangapple
  • 本文由 发表于 2014年10月16日 20:47:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/26404864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定