0

我在互联网上没有找到任何我的问题。我反序列化播放列表的数据。

他是我的代码:

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

感谢您的帮助

4

1 回答 1

0

为了确保 XML 的有效性,您需要定义一个 XML Schema。XML Schema 声明了在您的 XML 中允许使用哪些标记、以什么顺序以及使用什么类型的值。

是一篇关于如何根据 Schema 验证 XML 的文章。

如果您的 XML 格式不正确(例如,用户没有关闭标签或类似的东西),反序列化将失败,您将InvalidOperationExceptionInnerException. 请参阅MSDN 上的XmlSerializer.Deserialize()

于 2013-04-01T11:05:16.827 回答