我需要一些帮助来指出我在这里做错了什么。我搜索了SO并尝试了不同的方法来加载这个XML,我只是看不出会导致这个错误:
System.InvalidOperationException:XML文档(1,1)中存在错误。 ---> System.Xml.XmlException:根级别的数据无效。第1行,第1位。
<?xml version="1.0" encoding="utf-8"?>
<folderlist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<foldersetting>
<id>1</id>
<source>
<path>\\USApps2\AVL\Attachments</path>
<datelastread>2016-01-25T10:51:12.6030162-08:00</datelastread>
<filter>
<owner>US\</owner>
<filetype>*</filetype>
</filter>
</source>
<destination>
<path>E:\UserData\AVL</path>
<overwrite>false</overwrite>
</destination>
</foldersetting>
<foldersetting>
<id>2</id>
<source>
<path>\\TWAVLSVR\AVL\Attachments</path>
<datelastread>2016-01-22T10:51:12.6030162-08:00</datelastread>
<filter>
<owner>TW\</owner>
<filetype>PDF</filetype>
</filter>
</source>
<destination>
<path>E:\UserData\AVL</path>
<overwrite>false</overwrite>
</destination>
</foldersetting>
<foldersetting>
<id>3</id>
<source>
<path>E:\UserData\AVL</path>
<datelastread>2016-01-22T10:51:12.6030162-08:00</datelastread>
<filter>
<owner>US\</owner>
<filetype>*</filetype>
</filter>
</source>
<destination>
<path>E:\UserData\AVL\Web</path>
<overwrite>false</overwrite>
</destination>
</foldersetting>
</folderlist>
这是我的班级定义:
[Serializable()]
public class Filter
{
[XmlElement("owner")]
public string Owner {get; set;}
[XmlElement("filetype")]
public string FileType { get; set; }
}
[Serializable()]
public class SourceFolder
{
[XmlElement("path")]
public string Path { get; set; }
[XmlElement("datelastread")]
public DateTime DateLastRead { get; set; }
[XmlElement("filter")]
public Filter FilterTypes { get; set; }
}
[Serializable()]
public class DestinationFolder
{
[XmlElement("path")]
public string Path { get; set; }
[XmlElement("overwrite")]
public bool OverWrite { get; set; }
}
[Serializable()]
public class FolderSetting
{
[XmlElement("id")]
public int ID { get; set; }
[XmlElement("source")]
public SourceFolder Source { get; set; }
[XmlElement("destination")]
public DestinationFolder Destination { get; set; }
}
[Serializable()]
[XmlRoot("folderlist")]
public class FolderList
{
public FolderList()
{
FolderSettings = new List<FolderSetting>();
}
[XmlElement("foldersetting")]
public List<FolderSetting> FolderSettings;
}
这里我反序列化XML:
XmlSerializer serializer = new XmlSerializer(typeof(FolderList));
using (StringReader reader = new StringReader("C:\\Folders.xml"))
{
FolderList folders = (FolderList)(serializer.Deserialize(reader));
}
我在这里遵循了一个建议来填充我所拥有的类并对其进行序列化以确保我获得了适合我的类的格式,但它仍然没有帮助。希望有人能看到我在这里失踪的东西。
答案 0 :(得分:1)
问题是在反序列化中使用StringReader,你应该使用StreamReader:
using (StreamReader reader = new StreamReader("D:\\Folders.xml"))
{
FolderList folders = (FolderList)(serializer.Deserialize(reader));
}
因此,结果是序列化程序试图反序列化&#34; D:\ Folders.xml&#34;而不是OP尝试反序列化的数据文件。
答案 1 :(得分:0)
您的XML缺少&lt; / folderlist&gt;结束标记。
您可以在此处验证您的XML:http://www.xmlvalidation.com/
作为个人编码风格,请考虑使用常规开始课程并转到特定课程。当您首先看到顶级对象时,它更容易阅读。