I have the following C# class
[XmlRoot("Customer")]
public class MyClass
{
[XmlElement("CustId")]
public int Id {get;set;}
[XmlElement("CustName")]
public string Name {get;set;}
}
I then use the following function serialise the class object to Xml
public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
{
XmlSerializer serializer =
new XmlSerializer(obj.GetType(), new XmlRootAttribute("Response"));
using (MemoryStream ms = new MemoryStream())
{
XmlDocument xmlDoc = new XmlDocument();
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
}
}
My current output to XML is like;
<Response>
<CustId></CustId>
<CustName></CustName>
</Response>
But how can I get the response to look like;
<Response>
<Customer>
<CustId></CustId>
<CustName></CustName>
</Customer>
</Response>
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Definition and Usage The serialize() function converts a storable representation of a value. To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a memory buffer, or transmitted across a network.
To serialize a . Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to . Net object using Deserialize<T> or DeserializeObject methods.
Change the XmlElementAttribute
on MyClass
(it's not actually valid there according to http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute(v=vs.110).aspx) to an XmlTypeAttribute
:
[XmlType("Customer")]
public class MyClass
{
[XmlElement("CustId")]
public int Id { get; set; }
[XmlElement("CustName")]
public string Name { get; set; }
}
The serialization method can now be (identical to that in the question but without the second parameter in the constructor of XmlSerializer
):
public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlDocument xmlDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
serializer.Serialize(ms, obj);
ms.Position = 0;
xmlDoc.Load(ms);
}
return xmlDoc;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With