使用 XDocument 加载编码为 UTF 16 的 xml

编程入门 行业动态 更新时间:2024-10-13 18:20:24
本文介绍了使用 XDocument 加载编码为 UTF 16 的 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-27 12:15:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   XDocument   UTF   xml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!