0

我正在尝试反序列化以下 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 个项目,但具有公牛属性值。错误可能与我的类定义有关。

请帮忙。

4

1 回答 1

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; }
}
于 2013-10-01T00:04:24.040 回答