views:

758

answers:

2

XDocument.Load throws exception, when using XML file name of xml with version 1.1 instead of 1.0

Any clean solutions to resolve the error (No regex) and load the document?

+3  A: 

Initial reaction, just to confirm that I can reproduce this:

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);
    }
}

Results in this exception:

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)

It fails on both .NET 3.5 and .NET 4.0 beta 1.

Jon Skeet
The problem is right, do you have a clean solution (No regex).
Priyank Bolia
I concluded the same... (although I didn't check 4.0; +1 for extra effort)
Marc Gravell
Reviewing XmlReader.Create for the XmlReaderSettings, ConformanceLevel.Document states it needs an XML 1.0 document.
sixlettervariables
+1  A: 

"Version 1.0" is hardcoded in various places in the standard .NET XML libraries. For example, your code seems to be falling foul of this line in System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(bool):

 if (!XmlConvert.StrEqual(this.ps.chars, this.ps.charPos, charPos - this.ps.charPos, "1.0"))

I had a similar issue with XDocument.Save refusing to retain 1.1. It was the same type of thing - a hardcoded "1.0" in a System.Xml method.

I couldn't find anyway round it that still used the standard libraries.

dommer