XML Error: XmlException: invalid data.

I’m having one of those moments where I’m about to toss my laptop out the window. I’ve successfully loaded complex XML sheets in the past with no problem, but right now I’m losing my mind. Everytime I load this particular XML sheet, I get this error:

XmlException: invalid data.
System.Xml.XmlStreamReader.Read
(System.Char dest_buffer, Int32
index, Int32 count)

Here’s what the XML looks like:

> 
> <quotes>
    <quoteSet>
        <name>Thomas</name>
        <quote>The only way to discourage the gun culture is to remove the guns from the hands and shoulders of people who are not in the law enforcement business.</quote>
    </quoteSet>
    <quoteSet>
    <name>Sarah</name>
    <quote>Every civilized society must disarm its citizens against each other</quote>
    </quoteSet>
</quotes>

Here’s the code to read it:

XmlDocument XMLFile = new XmlDocument();
XMLFile.Load(“Assets/quotesUpdated2.xml”);

Any idea what could be up? Its a massively uninformative error and I’ve been fighting it for about 3.5 hours now. Help, please.

Hi, were you able to resolve this issue? If so, how?

Set encoding to ANSI. I had it on UTF-8 when the error occured. It worked for me. (I am using Notepad++)

The question is old, but I found it when looking for a similar problem today, and no answer was given so far.

Provided that your XML is otherwise correct (make the “drag the file to a browser”-Test, there is quite something mysterious going on with Unity FileStreams. Somehow Unity seems to modify them before actually giving access to the data, garbling them somehow when it comes to XML loading.

My workaround looks as follows:

I suppose you are using the “fairly standard” deserializiation:

using( var stream = new FileStream( path ) ) {
	var formatter = new System.Xml.Serialization.XmlSerializer( typeof( MyDataClass ) );
	mydata = (MyDataClass)formatter.Deserialize( stream );
	stream.Close();
}

Instead, try the following:

byte[] rawdata = File.ReadAllBytes( path );
using( var stream = new MemoryStream( rawdata ) ) {
	var formatter = new System.Xml.Serialization.XmlSerializer( typeof( MyDataClass ) );
	mydata = (MyDataClass)formatter.Deserialize( stream );
	stream.Close();
}

I’m fully aware that this is definitely not memory-efficient way to read a file, and you’ll run into memory trouble with big files. But it circumvents any hidden behaviour Unity has implemented in their filestreams, and basically, it fixed my similar problems and works.