如何在编码 utf-8 中读取 XML 文件 [英] How to read XML file in Encoding utf-8

查看:45
本文介绍了如何在编码 utf-8 中读取 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取包含一些中文字符的 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:

如果您看到相同的乱码文本,则您实际上并没有创建 UTF8 编码的 xml,而是其他内容.

If you see the same garbled text, you did not actually create UTF8 encoded xml, but something else.

回到你的问题:
由于您没有向我们提供很多信息,首先您是如何解析 XML 的,这里是您将如何使用 UTF8 专门解析它的示例:

Back to your question:
Since you don't give us a lot of info how you parse the XML in the first place here is an example of how you would specifically parse it with 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 文档的字符串.

Also if you want to optimize this you might not want pass in a stream rather than the string containing the entire xml document.

这篇关于如何在编码 utf-8 中读取 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆