XDocument无法在C#LINQ中加载版本1.1的xml?

Pri*_*lia 9 c# xml linq linq-to-xml

XDocument.Load 使用版本1.1而不是1.0的XML文件时抛出异常:

Unhandled Exception: System.Xml.XmlException: Version number '1.1' is invalid. Line 1, position 16.

任何干净的解决方案来解决错误(没有正则表达式)并加载文档?

Jon*_*eet 5

最初的反应,只是为了确认我可以重现这个:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此例外的结果:

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)
Run Code Online (Sandbox Code Playgroud)

从.NET 4.6开始,它仍然失败.

  • 查看XmlReader.Create以获取XmlReaderSettings,ConformanceLevel.Document声明它需要XML 1.0文档. (2认同)
  • 它在.NET 4.6 RC上失败. (2认同)

dom*_*mer 5

"1.0版"在标准.NET XML库的各个地方都是硬编码的.例如,你的代码似乎在System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(bool)中违反了这一行:

 if (!XmlConvert.StrEqual(this.ps.chars, this.ps.charPos, charPos - this.ps.charPos, "1.0"))
Run Code Online (Sandbox Code Playgroud)

我有一个类似的问题与XDocument.Save拒绝保留1.1.它是同一类型的东西 - System.Xml方法中的硬编码"1.0".

我还是找不到它仍然使用标准库.