Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument can't load xml with version 1.1 in C# LINQ?

XDocument.Load throws an exception when using an XML file with version 1.1 instead of 1.0:

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

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

like image 202
Priyank Bolia Avatar asked May 26 '09 20:05

Priyank Bolia


People also ask

What is XDocument C#?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.

Which method read XML documents from file URL for stream?

If your application needs to know which encoding is used to read the stream, consider using an XmlTextReader object to read the stream, and then use the XmlTextReader.

Which of the following method is a valid method load the XML document for processing?

Load(XmlReader) Loads the XML document from the specified XmlReader.

What is the use of system XML Linq DLL?

Xml. Linq. dll to fix missing or corrupted dll errors.


2 Answers

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's still failing as of .NET 4.6.

like image 193
Jon Skeet Avatar answered Oct 21 '22 13:10

Jon Skeet


"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.

like image 40
dommer Avatar answered Oct 21 '22 14:10

dommer