使用 XDocument 加载编码为 UTF 16 的 xml [英] Loading xml with encoding UTF 16 using XDocument

查看:29
本文介绍了使用 XDocument 加载编码为 UTF 16 的 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 XDocument 方法读取 xml 文档.但是当 xml 有

I am trying to read the xml document using XDocument method . but i am getting an error when xml has

<?xml version="1.0" encoding="utf-16"?>

当我手动删除编码时,它工作得很好.

When i removed encoding manually.It works perfectly.

我收到错误没有 Unicode 字节顺序标记.无法切换到 Unicode."

我尝试搜索,然后我找到了这里-->

i tried searching and i landed up here-->

为什么 C# XmlDocument.包含 XML 标头时 LoadXml(string) 失败?

但无法解决我的问题.

我的代码:

XDocument xdoc = XDocument.Load(path);

有什么建议吗??

谢谢.

推荐答案

您尝试读取的文件似乎未编码为 Unicode.您可以通过尝试打开一个编码为 ANSI 的文件并在 XML 文件中指定为 utf-16 的编码来复制该行为.

It looks like the file you are trying to read is not encoded as Unicode. You can replicate the behavior by trying to open a file encoded as ANSI with the encoding in the XML file specified as utf-16.

如果不能保证文件编码正确,那么可以将文件读入流中(让StreamReader检测编码)然后创建XDocument代码>:

If you can't ensure that the file is encoded properly, then you can read the file into a stream (letting the StreamReader detect the encoding) and then create the XDocument:

using (StreamReader sr = new StreamReader(path, true))
{
    XDocument xdoc = XDocument.Load(sr);
}

这篇关于使用 XDocument 加载编码为 UTF 16 的 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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