Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Serialize C# Class with class name as root element

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>
like image 793
neildt Avatar asked Nov 08 '13 11:11

neildt


People also ask

What is serialization in C?

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.

What is the use of serialize ()?

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.

How do you serialize and deserialize a string in C#?

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.


1 Answers

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;
    }
like image 164
Lawrence Avatar answered Oct 02 '22 18:10

Lawrence