如何从XSD生成类,但保持属性相同?

时间:2014-11-03 19:41:31

标签: c# xml serialization xsd

我从数据库接收XML并尝试将其处理到我的系统中。我从其他团队收到的XSD中生成了一个类。我遇到的问题是,现在XSD中的属性名称与我的应用程序中的属性名称(典型值)不匹配。意思是为了让我构建一个我可以使用的对象,我必须创建一个对象并将其与XML拼凑在一起。像这样:

DynamicEntity auth = new DynamicEntity(EntityAuthorization);
auth.Properties["DealerId] = authprm.new_dealerid[0].Value;
auth.Properties["CarId"] = authprm.new_carid[0].Value;
etc...

我可能要设置40到100个属性。我已经考虑过将XmlElement应用于类属性,但每次我必须重新生成类(来自XML)时,我将丢失之前应用的XmlElements。有什么建议吗?

谢谢大家!

1 个答案:

答案 0 :(得分:1)

您可以将MetadataTypeAttribute放在班级上,使用元数据“伙伴班级”。我将使得生成部分的类(如果尚未生成),然后创建另一个部分类并将MetadataType属性添加到该类。然后,如果你从XSD重新生成类,并且它不是部分的,编译器会抱怨并且你会记得让它变成局部的。

我真的不喜欢“伙伴类”,因为这些属性会重复,而不是真正的DRY,但它可能是您正在寻找的解决方案。有关元数据类的简单概述,通常是关于验证属性的 - 但它适用于任何属性,您可以在MS here上找到

您可以看到答案https://stackoverflow.com/a/26724847/1798889,了解如何让XmlSerializer了解好友类。

<强>更新

现在,如果您不想使用Buddy类,我可以考虑这一点,您可以构建一个流畅的api来配置XML Serializer。

我们将保留XMLSerializer with buddy class question中的CustomAttributeProvider类,而是创建一个XmlSerializerConfigurator类。

public class XmlSerializerConfigurator<T>
{
    private readonly XmlAttributeOverrides _xmlAttributeOverrides;

    public XmlSerializerConfigurator(XmlAttributeOverrides xmlAttributeOverrides)
    {
        _xmlAttributeOverrides = xmlAttributeOverrides;
    }

    public XmlSerializerConfigurator() : this(new XmlAttributeOverrides())
    {
    }

    /// <summary>
    /// Adds attributes to properties or fields and strongly typed
    /// </summary>
    /// <typeparam name="TData"></typeparam>
    /// <param name="property"></param>
    /// <param name="xmlAttributes"></param>
    /// <returns></returns>
    public XmlSerializerConfigurator<T> AddPropertyOrFieldAttributes<TData>(Expression<Func<T, TData>> property,
                                                    params Attribute[] xmlAttributes)
    {
        var memberName = property.GetName();
        _xmlAttributeOverrides.Add(typeof (T), memberName,
                                   new XmlAttributes(new CustomAttributeProvider(xmlAttributes)));
        return this;
    }

    /// <summary>
    /// Adds class level attributes
    /// </summary>
    /// <param name="xmlAttributes"></param>
    /// <returns></returns>
    public XmlSerializerConfigurator<T> AddClassLevelAttributes(params Attribute[] xmlAttributes)
    {
        _xmlAttributeOverrides.Add(typeof(T), new XmlAttributes(new CustomAttributeProvider(xmlAttributes)));
        return this;
    }

    /// <summary>
    /// Creates an XmlSerializerConfigurator that is tied to the main one
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <returns></returns>
    public XmlSerializerConfigurator<K> ChildClassConfigurator<K>()
    {
        // passes in own XmlAttributeOverrides and since object reference it will fill the same object 
        return new XmlSerializerConfigurator<K>(_xmlAttributeOverrides);
    }

    /// <summary>
    /// Returns back an XmlSerializer with this configuration
    /// </summary>
    /// <returns></returns>
    public XmlSerializer GetSerializer()
    {
        return new XmlSerializer(typeof(T), _xmlAttributeOverrides);
    }
}

这个类允许你配置哪些属性在Serializer的类/属性上,而不依赖于buddy类。当类具有另一个类作为允许配置该类的属性时,我们需要ChildClassAttributes。

此外,我使用一个扩展方法,该方法从名为GetName的表达式返回一个属性或字段。

public static string GetName<TEntity, TData>(this Expression<Func<TEntity, TData>> field)
{
    var name = "";

    if (field.Body is MemberExpression)
    {
        var body = field.Body as MemberExpression;
        var ebody = body.Expression as MemberExpression;

        if (ebody != null)
        {
            name = ebody.Member.Name + ".";
        }
        name = name + body.Member.Name;
    }
    else if (field.Body is UnaryExpression)
    {
        var ubody = field.Body as UnaryExpression;
        var body = ubody.Operand as MemberExpression;
        var ebody = body.Expression as MemberExpression;

        if (ebody != null)
        {
            name = ebody.Member.Name + ".";
        }
        name = name + body.Member.Name;
    }
    else if (field.Body is ConstantExpression)
    {
        var cbody = field.Body as ConstantExpression;
        name = cbody.Value.ToString();
    }
    else
    {
        throw new InvalidOperationException(String.Format("{0} not supported.", field));
    }

    return name;
}

现在你可以这样使用/配置

var xmlConfiguration = new XmlSerializerConfigurator<Group>();
xmlConfiguration.AddPropertyOrFieldAttributes(x => x.Employees, new XmlArrayItemAttribute(typeof (Employee)),
                                              new XmlArrayItemAttribute(typeof (Manager)));
xmlConfiguration.AddClassLevelAttributes(new XmlRootAttribute("GroupName"));
var childConfiguration = xmlConfiguration.ChildClassConfigurator<Employee>();
childConfiguration.AddPropertyOrFieldAttributes(x => x.FullName, new XmlElementAttribute("Name"));
var xmlSerializer = xmlConfiguration.GetSerializer();

现在,所有属性和字段都是强类型的,并且不会在好友类中重复。