【问题标题】:XmlException in C#: Data at the root level is invalidC# 中的 XmlException:根级别的数据无效
【发布时间】:2014-06-01 01:56:43
【问题描述】:

当应用程序恢复时,我正在尝试在 C# WinRt 应用程序中读取 XML 文件:

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);
}

但我得到了System.Xml.XmlException

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

如何解决这个问题并正确读取文件?


我的 XML 文档是这样构造的:

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);

对于这样的文件:

<PreviousSessionData>...</PreviousSessionData>

【问题讨论】:

  • 请显示您的 XML 文件,至少前几行。

标签: c# xml windows-runtime linq-to-xml


【解决方案1】:

System.Xml.Linq.XDocument.Parseexpects an XML string,不是 XML 文件名。

这段代码是错误的(见 cmets):

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

你想要的是将文件的内容放在一个字符串中:

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

或者您可以使用XDocument.Load 哪个expects a file path,而不是字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 2019-12-15
    • 2014-01-17
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多