using System; using System.Data; using System.Xml; class DataTableXmlConversion { // DataTable 转 XML public static XmlDocument DataTableToXml(DataTable dt) { XmlDocument xmlDoc = new XmlDocument(); XmlElement root = xmlDoc.CreateElement("Data"); xmlDoc.AppendChild(root); foreach (DataRow row in dt.Rows) { XmlElement dataElement = xmlDoc.CreateElement("Record"); foreach (DataColumn column in dt.Columns) { XmlElement columnElement = xmlDoc.CreateElement(column.ColumnName); columnElement.InnerText = row[column.ColumnName].ToString(); dataElement.AppendChild(columnElement); } root.AppendChild(dataElement); } return xmlDoc; } // XML 转 DataTable public static DataTable XmlToDataTable(string xml) { DataTable dt = new DataTable(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNodeList recordNodes = xmlDoc.SelectNodes("//Record"); foreach (XmlNode recordNode in recordNodes) { DataRow newRow = dt.NewRow(); foreach (XmlNode columnNode in recordNode.ChildNodes) { newRow[columnNode.Name] = columnNode.InnerText; } dt.Rows.Add(newRow); } return dt; } }
推荐阅读