I am creating a service that accepts a stored procedure and user input from an ASP page and is supposed to return the data in XML format back to the page. I am having trouble trying to figure out how to accomplish this. Can anyone suggest a better way to go about this and/or explain the flaw in my method? At first I was returning a string with the method, then I tried to just write an XML document with the results of the stored procedure in an attempt to access the XML file on the ASP page.
I have not been able to find a good example to extrapolate from. Please let me know if more clarification is needed.
Thank you!
Here is the code-behind I have:public void DataExchange(string storedProcedure, string data)
{
string connString = ConfigurationManager.ConnectionStrings["DataExchangeConnString"].ConnectionString;
//string returnData = "";
int i = 0;
SqlParameter dataParameter = new SqlParameter();
dataParameter.Value = data;
dataParameter.ParameterName = "@data";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(storedProcedure, conn);
SqlDataReader reader = null;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(dataParameter);
try
{
conn.Open();
reader = cmd.ExecuteReader();
string FileName = @"..\xmlDOC\returnData.xml";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(reader.ToString(), connString);
DataSet objDataSet = new DataSet("Data");
// Fill DataSet
objDataAdapter.Fill(objDataSet, "Data");
// Write DataSet contents to file
objDataSet.WriteXml(FileName, XmlWriteMode.IgnoreSchema);
//while (reader.Read())
//{
// for (i = 0; i < reader.FieldCount; i++)
// {
// returnData += (reader[i] + "|");
// }
// return returnData;
//}
//return false.ToString();
}
catch (Exception)
{
throw;
}
finally
{
reader.Close();
conn.Close();
}
}
解决方案
Try this
With Genericspublic static string SerializeToXml(T value)
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, value);
return write.ToString();
}
Without Generics
public static string SerializeToXml(object value)
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
XmlSerializer serializer = new XmlSerializer(value.GetType());
serializer.Serialize(writer, value);
return writer.ToString();
}
To Deserializefunction T Deserialize(string s)
{
var serializer = new XmlSerializer(typeof(T));
var stringReader = new StringReader(serializedResults);
var obj = (T)serializer.Deserialize(stringReader);
stringReader.Dispose();
return obj;
}