序列化您的类并将 xml 对象放入数据库中,这是一个序列化类和函数的示例,用于与对象/xml 进行序列化:
VB.net
Imports System.Runtime.Serialization
Imports System.Xml
Imports System.IO
Imports System.Text
Namespace NamespaceGoesHere
<DataContract()> _
Public Class ClassNameGoesHere
'All your properties go here, for example:
<DataMember> Property PropertyName As String = "test"
'Note the use of <DataMember> and <DataContract()>
#Region "Serialisation"
Public Function Serialise() As String
Dim s As New System.IO.MemoryStream
Dim x As New DataContractSerializer(GetType(ClassNameGoesHere))
x.WriteObject(s, Me)
s.Position = 0
Dim sw As New StreamReader(s)
Dim str As String
str = sw.ReadToEnd()
Return str
End Function
Public Shared Function DeSerialise(xmlDocument As String) As ClassNameGoesHere
Dim doc As New XmlDocument
Dim ser As New DataContractSerializer(GetType(ClassNameGoesHere))
Dim stringWriter As New StringWriter()
Dim xmlWriter As New XmlTextWriter(stringWriter)
doc.LoadXml(xmlDocument)
doc.WriteTo(xmlWriter)
Dim stream As New MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()))
stream.Position = 0
Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, New XmlDictionaryReaderQuotas())
Return DirectCast(ser.ReadObject(reader, True), ClassNameGoesHere)
End Function
#End Region
End Class
End Namespace
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Text;
namespace NamespaceGoesHere
{
[DataContract()]
public class ClassNameGoesHere
{
//All your properties go here, for example:
[DataMember()]
public string PropertyName { get; set; }
//Note the use of [DataMember()] and [DataContract()]
#region "Serialisation"
public string Serialise()
{
System.IO.MemoryStream s = new System.IO.MemoryStream();
DataContractSerializer x = new DataContractSerializer(typeof(ClassNameGoesHere));
x.WriteObject(s, this);
s.Position = 0;
StreamReader sw = new StreamReader(s);
string str = null;
str = sw.ReadToEnd();
return str;
}
public static ClassNameGoesHere DeSerialise(string xmlDocument)
{
XmlDocument doc = new XmlDocument();
DataContractSerializer ser = new DataContractSerializer(typeof(ClassNameGoesHere));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
doc.LoadXml(xmlDocument);
doc.WriteTo(xmlWriter);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));
stream.Position = 0;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
return (ClassNameGoesHere)ser.ReadObject(reader, true);
}
#endregion
}
}
创建类后,您可以使用 serialise 函数将其序列化为 xml 字符串。将其存储在数据库中(我将使用 XML 数据类型,但您可以将其存储为 NVARCHAR(MAX)。从数据库返回时,只需调用传入字符串的反序列化函数,您将再次获取对象。