我想在 SQL 中保存一个 ac#.NET 类的实例以供以后检索。我可以使用 LINQ to SQL 添加一条完整的记录,其中包含构成该类的所有 xml。
现在如何检索该 xml 并重建类对象实例?
我想在 SQL 中保存一个 ac#.NET 类的实例以供以后检索。我可以使用 LINQ to SQL 添加一条完整的记录,其中包含构成该类的所有 xml。
现在如何检索该 xml 并重建类对象实例?
将您的对象序列化为 XML 字符串:
public static string ToXml<T>(T obj)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using (Stream stream = new MemoryStream())
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
new XmlSerializer(obj.GetType()).Serialize(writer, obj);
writer.Flush();
stream.Flush();
stream.Position = 0;
using (TextReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
将 XML 字符串反序列化为对象:
public static T FromXml<T>(string xml)
{
using (TextReader reader = new StringReader(xml))
{
try
{
return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
catch (InvalidOperationException)
{
// string passed is not XML, return default
return default(T);
}
}
}
正如其他人提到的,序列化可以解决问题,但要注意格式化程序/序列化程序,否则:
<?xml version="1.0" encoding="utf-8" ?>
将成为您的序列化的一部分。尽可能使用 DataContractSerializer。
我强烈建议你在做任何事情之前先看看这个:.NET XML Serialization without <?xml> text declaration 。
高温高压
我会推荐 xml 序列化和反序列化。
如果我有一个类 Person 定义为:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
从 XML 保存/加载它很简单:
Person donald = new Person{
ID=1,
FirstName="Donald",
LastName="Duck",
DateOfBirth=new DateTime(1950,1,1)};
//create a xml serializer with the required type
XmlSerializer xs=new XmlSerializer(typeof(Person));
//open a stream to the file, and save the instance
TextWriter tw = new StreamWriter(@"C:\donald.xml");
xs.Serialize(tw, donald);
tw.Close();
//open a reader stream to the file, and just load the instance.
TextReader tr = new StreamReader(@"C:\donald.xml");
Person donald2 = (Person) xs.Deserialize(tr);
tr.Close();
警告:这仅将类的公共属性/字段保存为 XML 元素。如果您想对生成的 XML 进行附加控制,请查看System.Xml.Serialization命名空间中的属性(XmlAttributeAttribute 是我个人最喜欢的),
您可能希望使用XStream将对象存储为 XML。它很容易使用。