c# - 序列化在运行时创建的类

标签 c# xml xml-serialization codedom system.reflection

我从不同的客户那里得到了多个 XSD,我需要向他们提供符合他们提供的 XSD 的 XML 格式的数据。我已经编写了一段代码,使用 codedom、System.Reflection 和 codeprovider 从 XSD 动态创建和编译一个类。 现在我的计划是通过多个查询从数据库中获取数据并将字段映射到创建的动态类的属性并将其序列化。我正在寻找一种映射这些字段的通用方法,它可用于任何类型的 xsd,并且只需映射它将序列化并提供 XML 文件的字段。至于查询,我将它们放在配置文件中。通用解决方案可行吗?关于如何去做的任何想法或指示?

最佳答案

我能够解决这个问题。以下是我使用的步骤:我首先使用反射和具有可序列化属性的 codedom.compiler 从 xsd 创建了一个内存中运行时程序集。使用反射,我在该程序集中创建了类的实例,并根据从数据库中获得的数据分配了属性。我转发给另一个序列化方法的这个类接受一个对象并将其序列化为 xml。

就映射而言,我确保数据库列名称需要与 xml 属性名称匹配,这样我才能映射和调用它们。

这是片段:

object fxClass = myAssembly.CreateInstance(cls.FullName);
Type t = fxClass.GetType();


var arrRates = Array.CreateInstance(t, tab.Rows.Count);
int i =0;
foreach (DataRow dr in tab.Rows)
{
    fxClass = myAssembly.CreateInstance(cls.FullName);
    PropertyInfo[] fxRateProperties = t.GetProperties();
    foreach (PropertyInfo prop in fxRateProperties)
    {
        string rowVal = dr[prop.Name].ToString();

        if (prop.PropertyType == typeof(DateTime))
        {
            prop.SetValue(fxClass, util.convertToDate(rowVal), null);
        }
        else if (prop.PropertyType == typeof(bool))
        {
            prop.SetValue(fxClass, util.convertToBoolean(rowVal), null);
        }
        else if (prop.PropertyType == typeof(decimal))
        {
            prop.SetValue(fxClass, util.convertToDecimal(rowVal), null);
        }
        else prop.SetValue(fxClass, rowVal, null);                                           
    }
    arrRates.SetValue(fxClass,i);
    i++;
}
myClass.GetType().GetProperty("ForexRates").SetValue(myClass, arrRates, null);

然后将 myClass 对象传递给接受对象类型的序列化方法,就这样

public void serializeXML(object portfolio, string xmlPath)
{
    XmlSerializer serial = new XmlSerializer(portfolio.GetType());
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    try
    {
        using (FileStream fs = new FileStream(xmlPath, FileMode.Create, FileAccess.Write))
        {
            using (XmlTextWriter tw = new XmlTextWriter(fs, Encoding.UTF8))
            {
                tw.Formatting = Formatting.Indented;
                serial.Serialize(tw, portfolio, ns);
            }
        }
     }
}

为此,现在我计划添加一个 UI 部分,其中将“ForexRates”等映射保存在数据库中,然后它会打开任何 xsd 类型。

非常感谢您的回复。

关于c# - 序列化在运行时创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222557/

相关文章:

c# - 为什么 String.CompareTo 不考虑字符串长度?

c# - 如何将自闭标签添加到xml中的元素?

c# - 字符串按长度拆分并仅按最近的空间拆分

xml - 本地可以引用一个xmlns吗?

c# - 如何使用 xs :any/##any and mixed in code generated by the XSD tool 的复杂类型

.net - 使用 XmlSeralizer 在 C# 中解析稍微不正常的 XML

c# - 如何使 switch 语句更面向对象?

C#反序列化XML到对象

c# - .NET序列化: Best practice to map classes to elements and properties to attributes?

c# - 3个带linq的嵌套组