将XML属性与类属性相关联

时间:2014-05-17 16:25:42

标签: c# xml asp.net-mvc

我正在使用C#构建MVC应用程序,目前正在开发一种方法,将xml文档加载到文件流中,并遍历节点并将数据保存到模型对象中。

一切正常,但我很难编写object属性和xml属性名之间的关系。我想知道是否有一种聪明的方法来关联这两个,所以我可以通过每个循环运行它。

这是我目前的代码并且它有效,但我想使其更通用

旧代码

var xmlDoc = LoadXmlFileIntoStream("WSAPayCode.xml");

                var elementCollection = ExtractDescendants(xmlDoc, "WSAPayCode");



                foreach (var element in elementCollection)
                {

                    var abbreviationChar = element.Attribute("AbbreviationChar");

                    var payCode = new PayCode
                    {
                        Name = element.Attribute("Name").Value,
                        AutoResolved = element.Attribute("AutoResolved").Value.IsBool(),
                        EditExcuseAbsn = element.Attribute("EditExcuseAbsn").Value.IsBool(),
                        PersistPceSw = element.Attribute("PersistPceSw").Value.IsBool(),
                        AbbreviationChar = (string)element.Attribute("AbbreviationChar"),
                        EditCntToCdotSw = element.Attribute("EditCntToCdotSw").Value.IsBool(),
                        EditAffShfTotal = element.Attribute("EditAffShfTotal").Value.IsBool(),
                        EditCntToOt = element.Attribute("EditCntToOt").Value.IsBool(),
                        PayUsingWeightedAverageRate = element.Attribute("PayUsingWeightedAverageRate").Value.IsBool(),
                        RequiresMgrApproval = element.Attribute("RequiresMgrApproval").Value.IsBool(),
                        WeightedAverageRateIsComputedDaily =
                            element.Attribute("WeightedAverageRateIsComputedDaily").Value.IsBool(),
                        JustAutoResExpAsWorked = element.Attribute("JustAutoResExpAsWorked").Value.IsBool(),
                        AssociatedDurationPayCodeName = element.Attribute("AssociatedDurationPayCodeName").Value,
                        WeightedAverageRateContributionsUseAnAdjustedRate =
                            element.Attribute("WeightedAverageRateContributionsUseAnAdjustedRate").Value.IsBool(),
                        ScheduleHoursType = element.Attribute("ScheduleHoursType").Value,
                        CheckAvlbltySw = element.Attribute("CheckAvlbltySw").Value.IsBool(),
                        WageAddition = (string)element.Attribute("WageAddition"),
                        VisibleInMainArea = element.Attribute("VisibleInMainArea").Value.IsBool(),
                        IsMoneyCategory = element.Attribute("IsMoneyCategory").Value.IsBool(),
                        AmountType = element.Attribute("AmountType").Value,
                        VisibleInReport = element.Attribute("VisibleInReport").Value.IsBool(),
                        ContributesToWeightedAverageRates =
                            element.Attribute("ContributesToWeightedAverageRates").Value.IsBool(),
                        UnjustAutoResExpAsWorked = (bool)element.Attribute("UnjustAutoResExpAsWorked"),
                        WageMultiply = (string)element.Attribute("WageMultiply"),
                        Type = (string)element.Attribute("Type"),
                        VisibleToUser = (bool)element.Attribute("VisibleToUser"),
                        CustomerId = _customerId,
                    };

                    _db.PayCodes.Add(payCode);
                    _db.SaveChanges();

                }

新代码 我编写了一些代码来通过xml文件进行交互并提取属性的名称 - Code Below(也有效)

var xmlDoc = LoadXmlFileIntoStream("WSAPayCode.xml");

                    var elementCollection = ExtractDescendants(xmlDoc, "WSAPayCode");

                    var nodeAttributes = xmlDoc.Descendants("WSAPayCode").Select(x => x.Attributes());

                    foreach (var attrs in nodeAttributes)
                    {
                        var _attribute = "";
                        foreach (var attr in attrs)
                        {
                            // This successfully reads through each attribute and pulls out the name of the attribut
                            _attribute = attr.Name.ToString();
                        }

                    }

问题我想解决

我现在要做的是实例化一个对象并遍历属性名称并将值保存到对象中的相应属性。即将OLD代码替换为动态地将值分配给对象属性的东西。

1 个答案:

答案 0 :(得分:0)

我会检查使用XML Serializers / Deserializers。在你的类中,你提供了属性是属性是元素还是属性的属性,然后让它为你处理剩下的属性。

您可以设置属性以匹配XML文档提供的内容,例如名称是元素还是属性等。

例如:

[XmlRoot("PayCode")]
public class PayCode
{
    [XmlElement("Name")
    public string Name { get; set;}

    ....
}

然后,反序列化到您的对象:

XmlSerializer serializer = new
XmlSerializer(typeof(PayCode));

FileStream fs = new FileStream(filename, FileMode.Open);
XmlReader reader = XmlReader.Create(fs);

PayCode payCode = (PayCode)serializer.Deserialize(reader);