我在互联网上没有找到任何我的问题。我反序列化播放列表的数据。
他是我的代码:
using (var fs = new FileStream("playlist.xml", FileMode.OpenOrCreate))
{
XmlSerializer xml = new XmlSerializer(typeof(ObservableCollection<Playlist>));
if (fs.Length > 0)
pl = (ObservableCollection<Playlist>)xml.Deserialize(fs);
else
pl = new ObservableCollection<Playlist>();
}
这是结果 XML:
<?xml version="1.0"?>
<ArrayOfPlaylist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Playlist>
<Name>Playlist1</Name>
<List>
<Media>
<path>C:\Users\Tchiko\Videos\Suit Tie (Official Lyric Video).mp4</path>
<name>Suit Tie (Official Lyric Video).mp4</name>
<type>Video</type>
</Media>
</List>
</Playlist>
<Playlist>
<Name>Hip hop</Name>
<List>
<Media>
<path>C:\Users\Tchiko\Videos\Suit Tie (Official Lyric Video).mp4</path>
<name>Suit Tie (Official Lyric Video).mp4</name>
<type>Video</type>
</Media>
</List>
</Playlist>
</ArrayOfPlaylist>
在加载我的播放列表之前,我想检查用户是否手动损坏了文件。我需要检查XML格式是否正确,以避免反序列化后发生冲突。
编辑: 避免错误格式错误的版本:
using (var fs = new FileStream("playlist.xml", FileMode.OpenOrCreate))
{
try
{
XmlSerializer xml = new XmlSerializer(typeof(ObservableCollection<Playlist>));
if (fs.Length > 0)
pl = (ObservableCollection<Playlist>)xml.Deserialize(fs);
else
pl = new ObservableCollection<Playlist>();
}
catch (Exception ex)
{
pl = new ObservableCollection<Playlist>();
}
}
感谢您的帮助