XDocument.Load
使用版本为 1.1 而不是 1.0 的 XML 文件时会引发异常:
未处理的异常:System.Xml.XmlException:版本号“1.1”无效。 1 号线,16 号位置。
有任何干净的解决方案来解决错误(没有正则表达式)并加载文档吗?
最初的反应,只是为了确认我可以重现这个:
using System;
using System.Xml.Linq;
class Test
{
static void Main(string[] args)
{
string xml = "<?xml version=\"1.1\" ?><root><sub /></root>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc);
}
}
导致此异常:
Unhandled Exception: System.Xml.XmlException: Version number '1.1' is invalid. Line 1, position 16.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(Boolean isTextDecl)
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text)
at Test.Main(String[] args)
从 .NET 4.6 开始仍然失败。
“版本 1.0”被硬编码在标准 .NET XML 库的各个位置。例如,您的代码似乎违反了 System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(bool):
中的这一行 if (!XmlConvert.StrEqual(this.ps.chars, this.ps.charPos, charPos - this.ps.charPos, "1.0"))
我也遇到了类似的问题,XDocument.Save 拒绝保留 1.1。这是同一类型的东西 - System.Xml 方法中的硬编码“1.0”。
无论如何我都找不到仍然使用标准库的地方。
您可以跳过第一行,然后使用 XDocument.Parse 加载 XML,如下所示:
var lines = File.ReadAllLines(xmlFilename).ToList();
lines[0] = String.Empty;
var xdoc = XDocument.Parse(string.Join("", lines));