how to serialize an object to XML, and vice versa
Hi,
Here is code sample of Serializing and Deserializing.There is also some additional methods to convert Byte Array in the sample.
i use serialize and deserialize actions by generic in C#
You can also tag any member of the class or struct to be shown in XML.
XMLAttribute marks the member as composite class,XMLElement marks the member as value of node as well
if you remark the struct as shown below;
[Serializable]
public class Group
{
[System.Xml.Serialization.XmlAttribute("id")]
public Guid GroupId;
[System.Xml.Serialization.XmlAttribute("text")]
public string Text;
[System.Xml.Serialization.XmlAttribute("type")]
public string Type;
[System.Xml.Serialization.XmlElement(ElementName = "Question")]
public List < question > Questions;
}
good luck.
Here is code sample of Serializing and Deserializing.There is also some additional methods to convert Byte Array in the sample.
i use serialize and deserialize actions by generic in C#
private Byte[] StringToUTF8ByteArray(String pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
//UTF8Encoding is under the System.Text namespace
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}
private string Serialize(T request)
{
//MemoryStream is in System.IO
//XMLSerializer is in System.Xml.Serialization
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, request);
return UTF8ByteArrayToString(memoryStream.ToArray());
}
}
private T Deserialize (string XmlizedString)
{
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlizedString)))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
return (T) xs.Deserialize(memoryStream);
}
}
You can also tag any member of the class or struct to be shown in XML.
XMLAttribute marks the member as composite class,XMLElement marks the member as value of node as well
if you remark the struct as shown below;
[Serializable]
public class Group
{
[System.Xml.Serialization.XmlAttribute("id")]
public Guid GroupId;
[System.Xml.Serialization.XmlAttribute("text")]
public string Text;
[System.Xml.Serialization.XmlAttribute("type")]
public string Type;
[System.Xml.Serialization.XmlElement(ElementName = "Question")]
public List < question > Questions;
}
Comments
Post a Comment