using System.Data; using System.Xml.Serialization; using System.Text; using System.Xml; namespace CallCenterApi.Common { public static class XmlFormatHelper { /// /// DataSet转XML字符串 /// /// /// public static string DataSetToXml(DataSet Ds) { string xmlStr = "\r\n"; xmlStr += ""; for (int i = 0; i < Ds.Tables.Count; i++) { xmlStr += GetTableSetXml("NewTable" + i, Ds.Tables[i]); } xmlStr += ""; return xmlStr; } /// /// DataSet转XML字符串 /// /// /// public static string DataSetToXmlTable(DataSet Ds) { string xmlStr = "\r\n"; xmlStr += ""; for (int i = 0; i < Ds.Tables.Count; i++) { xmlStr += GetTableSetXmlTable("NewTable" + i, Ds.Tables[i]); } xmlStr += ""; return xmlStr; } public static string GetTableSetXmlTable(string tableName, DataTable table) { string str = string.Empty; if (table.Rows.Count > 0) { for (int i = 0; i < table.Rows.Count; i++) { str += "<" + tableName + ">"; for (int j = 0; j < table.Columns.Count; j++) { string clName = table.Columns[j].ColumnName; str += "<" + clName + ">" + table.Rows[i][clName] + ""; } str += ""; } } else { str += "<" + tableName + ">"; str += "0"; str += ""; } return str; } public static string GetTableSetXml(string tableName, DataTable table) { string str = string.Empty; for (int i = 0; i < table.Rows.Count; i++) { str += "<" + tableName + ">"; for (int j = 0; j < table.Columns.Count; j++) { string clName = table.Columns[j].ColumnName; str += "<" + clName + ">" + table.Rows[i][clName] + ""; } str += ""; } return str; } /// /// 把字符串转成XML格式,字符串格式:{" ID:1,User:aaa "},仅限根目录下的子节点,附加根节点"Root" /// /// /// public static string StringToXml(string Souce) { StringBuilder str = new StringBuilder(); str.Append("\r\n"); str.Append("\r\n"); string[] _list = Souce.Split(','); for (int i = 0; i < _list.Length; i++) { string[] _temp = _list[i].Split(':'); str.Append("<" + _temp[0] + ">"); str.Append(_temp[1]); str.Append("\r\n"); } str.Append(""); return str.ToString(); } public static string ToXml(T item) { XmlSerializer serializer = new XmlSerializer(item.GetType()); StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb)) { serializer.Serialize(writer, item); return sb.ToString(); } } public static string ApiGetDataSetToXml(DataSet Ds) { string str = string.Empty; str += ""; str += ""; str += ""; str += ""; str += ""; str += ""; str += ""; if (Ds.Tables.Count > 1) { var table = Ds.Tables[1]; for (int i = 0; i < table.Rows.Count; i++) { str += ""; for (int j = 0; j < table.Columns.Count; j++) { string clName = table.Columns[j].ColumnName; str += "<" + clName + ">"; } str += ""; } } str += ""; str += ""; return str; } } }