对自定义对象的xml序列化的通用调用

时间:2015-04-09 07:20:14

标签: c# xml

我正在编写将对象序列化为xml文档的方法。我没有编译时错误,但它在运行时失败(InvalidCastException:无法转换类型' System.Data.Linq.DataQuery ....)的对象。任何帮助将受到高度赞赏。

public string CreateXML<T>(Object ClassObject)
    {
        XmlDocument xmlDoc = new XmlDocument();   


       System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(((T)ClassObject).GetType());

        using (MemoryStream xmlStream = new MemoryStream())
        {
            xmlSerializer.Serialize(xmlStream, ClassObject);
            xmlStream.Position = 0;

            xmlDoc.Load(xmlStream);
            return xmlDoc.InnerXml;
        }

    }

运行时错误: InvalidCastException:无法转换类型&System; System.Data.Linq.DataQuery`1 [LINQPad.User.tbl_car]&#39;输入&#39; LINQPad.User.tbl_car&#39;。

2 个答案:

答案 0 :(得分:1)

为什么要传递物体?只需将其更改为泛型类型即可正常工作:

public string CreateXML<T>(T ClassObject)
{
    XmlDocument xmlDoc = new XmlDocument();   //Represents an XML document, 
    // Initializes a new instance of the XmlDocument class.          
  //  XmlSerializer xmlSerializer = new XmlSerializer(ClassObject.GetType());
    var  xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    // Creates a stream whose backing store is memory. 
    using (MemoryStream xmlStream = new MemoryStream())
    {
        xmlSerializer.Serialize(xmlStream, ClassObject);
        xmlStream.Position = 0;
        //Loads the XML document from the specified string.
        xmlDoc.Load(xmlStream);
        return xmlDoc.InnerXml;
    }
   // return null;
}

答案 1 :(得分:0)

按照Stenzel非常有用的评论,我现在将我的查询结果转换为DataTable,如下所示,现在我将xml输出。

    public static class ToDataTableClass
{
    public static DataTable ToDataTable<T>(this List<T> items)
    {
        var tb = new DataTable(typeof(T).Name);
        //string tempHeaderString = "";

        PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in props)
        {
            tb.Columns.Add(prop.Name);
            //if (prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            //{
            //    tempHeaderString = prop.Name;
            //}
            //else
            //{
            //        tb.Columns.Add(prop.Name, prop.PropertyType);
            //}
        }

        foreach (var item in items)
        {
            var values = new object[props.Length];
            for (var i = 0; i < props.Length; i++)
            {
                values[i] = props[i].GetValue(item, null);
            }

            tb.Rows.Add(values);
        }

        return tb;
    }
}