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

3

11

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?

Accountancy answered 26/5, 2009 at 20:6 Comment(2)
What's the exception? can you post the xml ?Lengel
The default ConformanceLevel is Document, which according to MSDN states it needs an XML 1.1 document: msdn.microsoft.com/en-us/library/h2344bs2.aspxAdobe
T
6

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.

Thirzia answered 26/5, 2009 at 20:22 Comment(5)
The problem is right, do you have a clean solution (No regex).Accountancy
I concluded the same... (although I didn't check 4.0; +1 for extra effort)Allotment
Reviewing XmlReader.Create for the XmlReaderSettings, ConformanceLevel.Document states it needs an XML 1.0 document.Adobe
Confirmed still failing in the same way with .NET 4.5 and .NET 4.5.1.Helgeson
It fails on .NET 4.6 RC.Ottava
H
5

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

Heaney answered 26/5, 2009 at 20:40 Comment(0)
P
1

You can just skip the first line, then use XDocument.Parse to load the XML, like this:

                var lines = File.ReadAllLines(xmlFilename).ToList();
                lines[0] = String.Empty;
                var xdoc = XDocument.Parse(string.Join("", lines));
Polyphony answered 29/3, 2021 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.