C# 中的 doc.LoadXml() 方法用于将 XML 字符串加载到 XmlDocument 对象中进行解析。然而,如果 XML 字符串中包含了 <?xml version='1.0' encoding='utf-8'?> 声明,就会导致 doc.LoadXml() 方法报错。

这是因为 doc.LoadXml() 方法要求 XML 字符串中不包含 XML 声明,只能包含有效的 XML 元素。解决这个问题的方法有两种:

  1. 如果要解析的 XML 字符串中包含 XML 声明,则可以使用 doc.Load() 方法将 XML 字符串加载到 XmlDocument 对象中进行解析,而不是使用 doc.LoadXml() 方法。示例代码如下:
string xmlString = "<?xml version='1.0' encoding='utf-8'?><root><element>Value</element></root>";
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(xmlString));
  1. 如果要使用 doc.LoadXml() 方法解析 XML 字符串,可以在调用 doc.LoadXml() 方法前,将 XML 声明从字符串中移除。示例代码如下:
string xmlString = "<?xml version='1.0' encoding='utf-8'?><root><element>Value</element></root>";
xmlString = xmlString.Replace("<?xml version='1.0' encoding='utf-8'?>", "");
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);

使用上述方法之一,可以避免在调用 doc.LoadXml() 方法解析包含 XML 声明的字符串时报错。

C# doc.LoadXml() 解析带 XML 声明字符串报错的解决方法

原文地址: https://www.cveoy.top/t/topic/LSo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录