Wednesday, November 18, 2015

Data at the root level is invalid. Line 1, position 1.

I was recently working on a project that required using Xml so I naturally used LINQ-to-XML to load my documents.

Unfortunately, as soon as I used the XDocument.Parse method, I encountered this dreaded error message:

"Data at the root level is invalid.  Line 1, position 1."

Apparently, after doing some searching on the Internet, this error was very prevalent, though the solution was not readily obvious!

Fortunately, this article provides some insight on how to workaround this problem:

I ended up using a combination of an XmlReader as well as a set of XmlReader settings to ignore my DTD instruction in the Xml Document as follows:

public static string RemoveDeclarationFromXDocument(string xmlDoc)
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.DtdProcessing = DtdProcessing.Ignore; //Ignore any DTDs in the Xml Document
    XDocument xdoc;
    //The Xml Document is encoded using UTF-16 rather than UTF-8
    //therefore, you need to use Encoding.Unicode instead of Encoding.UTF8
    using (var xmlStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlDoc)))
        using (XmlReader xmlReader = XmlReader.Create(xmlStream, settings))
            xdoc = XDocument.Load(xmlReader);
    //The XDocument string provides the Xml Document without the Xml Declaration heading
    return xdoc.ToString();

No comments:

Post a Comment