DateSet结果集转成UnicodeXml格式
public static string ToUnicodeXML(DataSet ds)
{
System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder();
UnicodeEncoding UTF = new UnicodeEncoding();
StrBuilder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
StrBuilder.Append("<DATAPACKET Version=\"2.0\">");
StrBuilder.Append("<METADATA><FIELDS>");
int FieldCount = ds.Tables[0].Columns.Count;
for (int i = 0; i < FieldCount; i++)
{
DataColumn dc = ds.Tables[0].Columns[i];
string FieldType = dc.DataType.Name.ToLower();
if (FieldType.ToLower() == "byte")
FieldType = "i2";
if (FieldType.ToLower() == "int32")
FieldType = "i4";
if (FieldType.ToLower() == "int64")
FieldType = "i8";
if ((FieldType.ToLower() == "single"))
FieldType = "r8";
if (FieldType.ToLower() == "string" && dc.MaxLength > 255)
FieldType = "bin.hex";
if (FieldType.ToLower() == "byte[]")
FieldType = "bin.hex";
if (FieldType.ToLower() == "datetime")
FieldType = "dateTime";
if (FieldType.ToLower() == "decimal")
StrBuilder.Append(string.Format("<FIELD attrname=\"{0}\" fieldtype=\"fixed\" ", dc.ColumnName));
else
StrBuilder.Append(string.Format("<FIELD attrname=\"{0}\" fieldtype=\"{1}\" ", dc.ColumnName, FieldType));
if (FieldType == "bin.hex" && dc.DataType.Name.ToLower() == "string")
StrBuilder.Append("SUBTYPE=\"Text\" ");
else if (FieldType.ToLower() == "string")
{
if (dc.MaxLength > 0)
StrBuilder.Append(string.Format("WIDTH=\"{0}\" ", dc.MaxLength));
else
StrBuilder.Append(string.Format("WIDTH=\"{0}\" ", 255));
}
else if ((FieldType.ToLower() == "sqldatetime"))
StrBuilder.Append("SUBTYPE=\"Formatted\"");
else if (FieldType == "bin.hex" && dc.DataType.Name.ToLower() != "string" || dc.DataType.Name.ToLower() == "byte[]")
StrBuilder.Append("SUBTYPE=\"Binary\"");
else if (FieldType.ToLower() == "decimal")
{
StrBuilder.Append(string.Format("DECIMALS=\"8\" WIDTH=\"20\"", dc.MaxLength));
}
StrBuilder.Append("/>");
}
StrBuilder.Append("</FIELDS><PARAMS/></METADATA>");
StrBuilder.Append("<ROWDATA>");
int RowCount = ds.Tables[0].Rows.Count;
for (int i = 0; i < RowCount; i++)
{
StrBuilder.Append("<ROW RowState=\"4\" ");
for (int j = 0; j < FieldCount; j++)
{
DataTable dt = ds.Tables[0];
string value = dt.Rows[i].ItemArray[j].ToString();
value = value.Replace("\"", """);
StrBuilder.Append(string.Format("{0}=\"{1}\" ",
dt.Columns[j].ColumnName,
value));
}
StrBuilder.Append("/>");
}
StrBuilder.Append("</ROWDATA></DATAPACKET>");
return StrBuilder.ToString();
}