反序列化xml返回空数组

时间:2013-09-30 23:49:44

标签: c# xml xml-serialization

我正在尝试反序列化以下xml:

<?xml version="1.0" encoding="utf-8"?>
  <Themes>
    <Theme Title="Default" Name="" SpriteCssClass="ThemeDefaultImage"></Theme>
    <Theme Title="DevExpress Style" Name="DevEx" SpriteCssClass="ThemeDevExImage"></Theme>
    <Theme Title="Metropolis" Name="Metropolis" SpriteCssClass="ThemeMetropolisImage"></Theme>
    <Theme Title="Metropolis Blue" Name="MetropolisBlue" SpriteCssClass="ThemeMetropolisBlueImage"></Theme>
    <Theme Title="Aqua" Name="Aqua" SpriteCssClass="ThemeAquaImage"></Theme>
    <Theme Title="Glass" Name="Glass" SpriteCssClass="ThemeGlassImage"></Theme>
    <Theme Title="Black Glass" Name="BlackGlass" SpriteCssClass="ThemeBlackGlassImage"></Theme>
    <Theme Title="Plastic Blue" Name="PlasticBlue" SpriteCssClass="ThemePlasticBlueImage"></Theme>
    <Theme Title="Red Wine" Name="RedWine" SpriteCssClass="ThemeRedWineImage"></Theme>
    <Theme Title="Soft Orange" Name="SoftOrange" SpriteCssClass="ThemeSoftOrangeImage"></Theme>
    <Theme Title="Youthful" Name="Youthful" SpriteCssClass="ThemeYouthfulImage"></Theme>
    <Theme Title="Office 2010 Blue" Name="Office2010Blue" SpriteCssClass="ThemeOffice2010BlueImage"></Theme>
    <Theme Title="Office 2010 Black" Name="Office2010Black" SpriteCssClass="ThemeOffice2010BlackImage"></Theme>
    <Theme Title="Office 2010 Silver" Name="Office2010Silver" SpriteCssClass="ThemeOffice2010SilverImage"></Theme>
    <Theme Title="Office 2003 Blue" Name="Office2003Blue" SpriteCssClass="ThemeOffice2003BlueImage"></Theme>
    <Theme Title="Office 2003 Olive" Name="Office2003Olive" SpriteCssClass="ThemeOffice2003OliveImage"></Theme>
    <Theme Title="Office 2003 Silver" Name="Office2003Silver" SpriteCssClass="ThemeOffice2003SilverImage"></Theme>
  </Themes>

使用以下类:

[Serializable]
public class Theme
{       
    [XmlElement("Title")]
    public string Title { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("SpriteCssClass")]
    public string SpriteCssClass { get; set; }
}

[Serializable]
[System.Xml.Serialization.XmlRootAttribute("Themes")]
public class ThemeCollection
{
    [XmlElement("Theme")]
    public Theme[] Themes { get; set; }
}

使用以下代码:

using (Stream stream = System.IO.File.OpenRead(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Themes.xml")))
{
    XmlSerializer serializer = new XmlSerializer(typeof(ThemeCollection));
    objThemeModel = (ThemeCollection)serializer.Deserialize(stream);
    stream.Close();
}

但是,代码执行成功但空集中的集合。我能够从xml中提取所有17个项目,但具有bull属性值。错误可能与我的类定义有关。

请帮助。

1 个答案:

答案 0 :(得分:1)

班级Theme应使用XmlAttribute代替XmlElement

[Serializable]
public class Theme
{       
    [XmlAttribute("Title")]
    public string Title { get; set; }
    [XmlAttribute("Name")]
    public string Name { get; set; }
    [XmlAttribute("SpriteCssClass")]
    public string SpriteCssClass { get; set; }
}