CodeGo.net>反序列化从SQL查询返回的XML对象?
作者:互联网
我需要反序列化从SQL查询返回的XML对象.
我使用JSON进行此操作,但是无法使用JSON,因此我转向了XML. JsonConvert功能可以将我的结果写在一行中..但是我不确定如何处理SQL给我的东西.
当写入服务器时,表将Xdocument类型获取到xml数据类型单元格中.
if (do_sql_read)
{
List<string> usernames = new List<string>();
List<int> ids = new List<int>();
string sql_load;
Player player_after_load = new Player();
//multiple
string select_string = @"SELECT * FROM [Table]";
using (SqlConnection sql_connection_a = new SqlConnection( GetConnectionString() ) )
{
sql_connection_a.Open();
using (SqlCommand command = new SqlCommand(select_string, sql_connection_a))
{
SqlDataReader reader = command.ExecuteReader(CommandBehavior.Default);
// XML VERSION
while (reader.Read())
{
int iii = reader.GetInt32(0); // unique id int
string name = reader.GetString(1); // Name string
sql_load = reader.GetString(2);
usernames.Add(name);
ids.Add(iii);
XmlSerializer XML_serializer = new XmlSerializer (typeof(Player));
// <<<<< THIS PART ??? >>>
player_after_load = (Player)XML_serializer.Deserialize (sql_load);
Console.WriteLine("SQLPlayer: " + iii + " " + player_after_load.name + " " + player_after_load.health + " " + player_after_load.mana);
}
/* JSON VERSION WORKS
while (reader.Read())
{
int iii = reader.GetInt32(0); // unique id int
string name = reader.GetString(1); // Name string
sql_load = reader.GetString(2);
usernames.Add(name);
ids.Add(iii);
player_after_load = JsonConvert.DeserializeObject<Player>(sql_load);
Console.WriteLine("SQLPlayer: " + iii + " " + player_after_load.name + " " + player_after_load.health + " " + player_after_load.mana);
}
*/
}
}
} // end do_sql_string
解决方法:
我仅添加此答案,因为您说不能使用System.IO.如果可以使用System.IO,请参考DatVM的答案.这是您可以做什么的示例.我对此进行了简化,使其包括要反序列化的类,并且可以在任何控制台应用程序中运行.
using System;
using System.Xml;
using System.Xml.Serialization;
public class Player
{
public string Name {get; set;}
}
public class Program
{
public static void Main()
{
var str = "<Player><Name>Bobby</Name></Player>";
var doc = new XmlDocument();
var XML_serializer = new XmlSerializer(typeof(Player));
doc.LoadXml(str);
Player player_after_load;
using (var nodeReader = new XmlNodeReader(doc))
{
player_after_load = (Player)XML_serializer.Deserialize(nodeReader);
}
Console.WriteLine(player_after_load.Name);
}
}
控制台结果
Bobby
标签:deserialization,xml,sql,c 来源: https://codeday.me/bug/20191120/2040952.html