user3651656
user3651656

Reputation: 185

XmlException in C#: Data at the root level is invalid

I'm trying to read an XML file in a C# WinRt app when the app resumes:

Windows.Storage.StorageFile File = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFileAsync("PreviousSession.xml");
if (File != null)
{
    var File2 = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFileAsync("PreviousSession.xml");
    string Document = File2.ToString();
    System.Xml.Linq.XDocument.Parse(Document);
}

But I get a System.Xml.XmlException:

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

How can I fix this and read the file properly?


My XML document is being constructed like this:

Windows.Data.Xml.Dom.XmlDocument Document = new Windows.Data.Xml.Dom.XmlDocument();
Windows.Data.Xml.Dom.XmlElement Element = (Windows.Data.Xml.Dom.XmlElement)Document.AppendChild(Document.CreateElement("PreviousSessionData"));
...
Windows.Storage.IStorageFile TempFile = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync("PreviousSession.xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Document.SaveToFileAsync(TempFile);

For a file like this:

<PreviousSessionData>...</PreviousSessionData>

Upvotes: 0

Views: 4076

Answers (1)

quantdev
quantdev

Reputation: 23793

System.Xml.Linq.XDocument.Parse expects an XML string, not an XML File name.

This code is wrong (see comments) :

string Document = File2.ToString();          // Return the name of "File2" object, not File2 content!
System.Xml.Linq.XDocument.Parse(Document);   // Parse error, trying to parse the string "PreviousSession.xml" !

What you want is put the content of the file in a string:

string Document = File.ReadAllLines(File2);
System.Xml.Linq.XDocument.Parse(Document); 

Or you can use XDocument.Load which expects a file path, not a string.

Upvotes: 1

Related Questions