反序列化 XML 返回空数组

本文关键字:数组 返回 XML 反序列化 | 更新日期: 2023-09-27 18:33:20

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

请帮忙。

反序列化 XML 返回空数组

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