问题描述
我正在尝试读取包含一些中文字符的 XML 文件.在文件中写入信息时,UTF-8 编码正常工作,中文字符正确写入文件.但是当我尝试阅读它时,它显示了一些??????相反.
I'm trying to read an XML file which has some Chinese characters in it. While writing the information in the file, encoding UTF-8 works properly and Chinese characters are written in the file properly. But when I try to read it it shows some ????? instead.
我只是想知道是否有人已经遇到过这个问题并且可以给我一些线索.
I'm just wondering if there is anyone who has already encountered whit this problem and can give me some clue.
推荐答案
首先,请确保数据在 UTF8 中确实是可读的,你这样做的方法是:
First, please make sure the data is actually readable in UTF8, the way you do this is:
- 下载一个记事本,让您指定用于查看文档的编码,例如 Notepad2.
- 在 Notepad2 中打开您的文档
- 文件 -> 编码 -> UTF8
如果您看到相同的乱码文本,则您实际上并没有创建 UTF8 编码的 xml,而是其他内容.
If you see the same garbled text, you did not actually create UTF8 encoded xml, but something else.
回到你的问题:
由于您没有向我们提供很多信息,首先您是如何解析 XML 的,这里是您将如何使用 UTF8 专门解析它的示例:
var xmlDoc = XDocument.Parse(
File.ReadAllText("filelocation", System.Text.Encoding.UTF8));
XDocument
类是 System.Xml.Linq
命名空间的一部分.
The XDocument
class is part for the System.Xml.Linq
namespace.
此外,如果您想优化它,您可能不希望传入流而不是包含整个 xml 文档的字符串.
这篇关于如何在编码 utf-8 中读取 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!