问题描述
限时送ChatGPT账号..我正在尝试使用 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屋!
更多推荐
[db:关键词]
发布评论