2个回答
展开全部
你可以把xml先转成DataTable再用这个方法转成JSON
DataSet(DataTable)与XML互转:http://blog.csdn.net/onlyzhangqin/archive/2008/04/05/2253965.aspx
public static string DataTableToJSON(DataTable table)
{
StringBuilder json = new StringBuilder();
json.Append("[");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
// json object
json.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
string columnName = table.Columns[j].ColumnName;
string columnType = table.Columns[j].DataType.Name;
// json field
if (columnType == "Int32" || columnType == "Int16" || columnType == "Decimal")
{
// don't surround numbers with quotes
json.AppendFormat("\"{0}\":\"{1}\"", columnName, row.IsNull(columnName) ? "" : row[columnName]);
}
else if (columnType == "Boolean")
{
// make the bool value lowercase
json.AppendFormat("\"{0}\":{1}", columnName, row.IsNull(columnName) ? "" : row[columnName].ToString().ToLower());
}
else
{
// everything else gets quotes around the data
json.AppendFormat("\"{0}\":\"{1}\"", columnName, row[columnName]);
}
if (j < table.Columns.Count - 1) json.Append(","); // add comma if not last column
}
json.Append("}");
if (i < table.Rows.Count - 1) json.Append(","); // add comma if not last row
}
json.Append("]");
return json.ToString();
}
DataSet(DataTable)与XML互转:http://blog.csdn.net/onlyzhangqin/archive/2008/04/05/2253965.aspx
public static string DataTableToJSON(DataTable table)
{
StringBuilder json = new StringBuilder();
json.Append("[");
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
// json object
json.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
string columnName = table.Columns[j].ColumnName;
string columnType = table.Columns[j].DataType.Name;
// json field
if (columnType == "Int32" || columnType == "Int16" || columnType == "Decimal")
{
// don't surround numbers with quotes
json.AppendFormat("\"{0}\":\"{1}\"", columnName, row.IsNull(columnName) ? "" : row[columnName]);
}
else if (columnType == "Boolean")
{
// make the bool value lowercase
json.AppendFormat("\"{0}\":{1}", columnName, row.IsNull(columnName) ? "" : row[columnName].ToString().ToLower());
}
else
{
// everything else gets quotes around the data
json.AppendFormat("\"{0}\":\"{1}\"", columnName, row[columnName]);
}
if (j < table.Columns.Count - 1) json.Append(","); // add comma if not last column
}
json.Append("}");
if (i < table.Rows.Count - 1) json.Append(","); // add comma if not last row
}
json.Append("]");
return json.ToString();
}
参考资料: http://blog.csdn.net/onlyzhangqin/archive/2008/04/05/2253965.aspx
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询