X3

RedSky

导航

c#datatable序列化xml

 

public static List<T> ToListModel<T>(this DataTable dt)
{
    if (dt.Rows.Count <= 0) return null;
    string typeName = typeof(T).Name;
    using (MemoryStream ms = new MemoryStream())
    {
        dt.WriteXml(ms);
        ms.Position = 0;
        using (StreamReader sr = new StreamReader(ms))
        {
            string title = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            string s = title + sr.ReadToEnd();
            s = s.Replace("&#x0;", "");
            s = s.Replace("<NewDataSet>", $"<ArrayOf{typeName} xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">")
                .Replace("</NewDataSet>", $"</ArrayOf{typeName}>")
                .Replace("<ds>", $"<{typeName}>").Replace("</ds>", $"</{typeName}>")
                .Replace("<Table>",$"<{typeName}>")
                .Replace("</Table>", $"</{typeName}>");
            return Common.XML.DeXMLSerialize<List<T>>(s);
        }
    }
}

 

public static T DeXMLSerialize<T>(string xmlString)
{
    T cloneObject = default(T);

    StringBuilder buffer = new StringBuilder();
    buffer.Append(xmlString);

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

    using (TextReader reader = new StringReader(buffer.ToString()))
    {
        Object obj = serializer.Deserialize(reader);
        cloneObject = (T)obj;
    }

    return cloneObject;
}

 

使用方法:

 1 var list = new DataTable().ToListModel<List<MyClass>>();

 MyClass:

1 public class MyClass {
2     [XmlElement("sql_column_name")]
3     public int MyProperty { get; set; }
4 }

 

posted on 2021-09-14 15:29  HotSky  阅读(369)  评论(0编辑  收藏  举报