将XML反序列化为简单的单个数组

时间:2018-01-25 17:00:40

标签: c# xml xml-deserialization

我需要将XML反序列化为一个简单的对象数组,但无法弄清楚如何执行它。这是我简化的XML:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Category[]), new XmlRootAttribute("rows"));

using (FileStream myFileStream = categoryFile.OpenRead())
{        
    var categoryArray = (Category[])xmlSerializer.Deserialize(myFileStream);
}

我已经为要反序列化的对象创建了类

using (var dbConnection = Program.Server.DatabaseHandler.Connection)
{
    dbConnection.SetQuery("SELECT users.id,users.username,users.rank,users.motto,users.look,users.gender,users.last_online,users.credits,users.activity_points,users.home_room,users.block_newfriends,users.hide_online,users.hide_inroom,users.vip,users.account_created,users.vip_points,users.machine_id,users.volume,users.chat_preference,users.focus_preference,users.pets_muted,users.bots_muted,users.advertising_report_blocked,users.last_change,users.gotw_points,users.ignore_invites,users.time_muted,users.allow_gifts,users.friend_bar_state,users.disable_forced_effects,users.allow_mimic,users.rank_vip " +
                          "FROM users " +
                          "JOIN user_auth_tickets " +
                          "ON users.id = user_auth_tickets.user_id " +
                          "WHERE user_auth_tickets.auth_ticket = @sso AND ip_last = @lastIp " +
                          "LIMIT 1"
    );

    dbConnection.AppendParameter("sso", authTicket);
    dbConnection.AppendParameter("lastIp", getIp());

    Load(dbConnection.ExecuteReader());
}

反序列化代码

public void Load(MySqlDataReader reader)
{
    while (reader.Read())
    {
        Id = reader.GetInt32("id");
        Username = reader.GetString("username");
        Credits = reader.GetInt32("credits");
        Diamonds = reader.GetInt32("vip_points");
        Duckets = reader.GetInt32("activity_points");
        Gender = reader.GetString("gender").ToUpper() == "M" ? PlayerGender.Male : PlayerGender.Female;
        Motto = reader.GetString("motto");
        Outfit = new PlayerOutfit(HabboUtilities.GetFilteredFigure(reader.GetString("look").ToLower()));
        Rank = reader.GetInt32("rank");
        HomeRoom = reader.GetInt32("home_room");
        VipId = reader.GetInt32("rank_vip");
    }
}

这显然不起作用,我已经尝试了各种XmlElement和XmlRoot标签,但我不太清楚我在做什么,所以我把所有这些都剥掉了以避免公开尴尬。感谢您的任何意见。

1 个答案:

答案 0 :(得分:2)

似乎您要反序列化的对象与您的xml文件没有完全兼容性。因此,在这种情况下,使用Linq到xml解决方案可能更灵活。

var xDocument = XDocument.Parse(xml);
var categoryList = xDocument.Descendants("fields").Select(x => new Category
{
    Name = x.Element("name").Value,
    Id = int.Parse(x.Element("id").Value)
});