{"id":62427,"date":"2022-01-17T07:50:56","date_gmt":"2022-01-17T06:50:56","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=62427"},"modified":"2022-01-17T08:02:17","modified_gmt":"2022-01-17T07:02:17","slug":"csharp-xml-serialization","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-xml-serialization\/","title":{"rendered":"Serializing Objects to XML in C#"},"content":{"rendered":"<p>In this post, we are going to learn about serializing objects to XML in C#.<\/p>\n<p>So, what is XML Serialization?\u00a0 <strong>It is the transformation of the public fields and property values of an object (without type information) into an XML stream.<\/strong><\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/xml-csharp\/XMLSerializationInCsharp\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>After the main definition, we can continue to see how to serialize objects to XML with several examples.\u00a0<\/p>\n<h2>How to Serialize a Simple Object to XML in C#<\/h2>\n<p>For serializing objects to XML in C#, we can use the <code>XmlSerializer<\/code> class from the <code>System.Xml.Serialization<\/code> namespace. We are going to start with the serialization of a simple C# class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Patient\r\n{\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public DateTime Birthday { get; set; }\r\n    public int RoomNo { get; set; }\r\n}<\/pre>\n<p>The <code>Patient<\/code> class contains the necessary information for a hospital patient.<\/p>\n<p>Next, let&#8217;s create a new object of type <code>Patient<\/code>. We are going to serialize it into an XML file using the <code>XmlSerializer<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patient = new Patient()\r\n{\r\n    ID = 232323,\r\n    FirstName = \"John\",\r\n    LastName = \"Doe\",\r\n    Birthday = new DateTime(1990, 12, 30),\r\n    RoomNo = 310\r\n};\r\n\r\nvar serializer = new XmlSerializer(typeof(Patient));\r\nusing (var writer = new StreamWriter(\"patients.xml\"))\r\n{\r\n    serializer.Serialize(writer, patient);\r\n}\r\n<\/pre>\n<p>Here, we create an <code>XMLSerializer<\/code> object that will serialize objects of type <code>Patient<\/code>. The <code>Serialize()<\/code> method transforms the object into XML. It also uses a <code>StreamWriter<\/code> object to write the XML into a file.<\/p>\n<p>The resulting XML file consists of an XML Root Element and all the information of the <code>Patient<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;Patient xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\"&gt;\r\n  &lt;ID&gt;232323&lt;\/ID&gt;\r\n  &lt;FirstName&gt;John&lt;\/FirstName&gt;\r\n  &lt;LastName&gt;Doe&lt;\/LastName&gt;\r\n  &lt;Birthday&gt;1990-12-30T00:00:00&lt;\/Birthday&gt;\r\n  &lt;RoomNo&gt;310&lt;\/RoomNo&gt;\r\n&lt;\/Patient&gt;<\/pre>\n<p>Note that the tags of the XML elements have exactly the same name as the properties of the <code>Patient<\/code> object. We can change their names with the use of <strong>C# Attributes<\/strong>, as we will see later on.<\/p>\n<h3>Things to Note About Serialization in C#<\/h3>\n<p>There are some important details about XML serialization in C# that we should be aware of. <strong>First of all, every class that we want to serialize should define the default (parameterless) constructor.<\/strong> In our case, we have not defined any constructors. Therefore, the parameterless constructor is included by default.<\/p>\n<p>Moreover, <strong>only the public members of a class will be serialized; private members will be omitted from the XML document<\/strong>.<\/p>\n<p><strong>The properties must have a public getter method<\/strong>. If they also have a setter method, this must be public too.<\/p>\n<h2>Serializing Classes with Nested Classes to XML<\/h2>\n<p>We can also serialize classes that contain objects from other classes.\u00a0<\/p>\n<p>Let&#8217;s introduce a new class that contains information about the patient&#8217;s home address:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Address\r\n{\r\n    public string Street { get; set; }\r\n    public string Zip { get; set; }\r\n    public string City { get; set; }\r\n    public string Country { get; set; }\r\n}<\/pre>\n<p>Next, we are going to modify the <code>Patient<\/code> with a reference to <code>Address<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8\">public class Patient\r\n{\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public DateTime Birthday { get; set; }\r\n    public int RoomNo { get; set; }\r\n    public Address HomeAddress { get; set; }\r\n}<\/pre>\n<p>To serialize the <code>patient<\/code> object, we are going to use the <code>XmlSerializer<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patient = new Patient()\r\n{\r\n    ID = 232323,\r\n    FirstName = \"John\",\r\n    LastName = \"Doe\",\r\n    Birthday = new DateTime(1990, 12, 30),\r\n    RoomNo = 310,\r\n    HomeAddress = new Address()\r\n    {\r\n        Street = \"12 Main str.\",\r\n        Zip = \"23322\",\r\n        City = \"Boston\",\r\n        Country = \"USA\",\r\n    }\r\n};\r\n\r\nvar serializer = new XmlSerializer(typeof(Patient));\r\nusing (var writer = new StreamWriter(\"patients.xml\"))\r\n{\r\n    serializer.Serialize(writer, patient);\r\n}\r\n<\/pre>\n<p>The resulting XML is going to have an additional element with the patient&#8217;s address details:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\" data-enlighter-highlight=\"8-13\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;Patient xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\"&gt;\r\n  &lt;ID&gt;232323&lt;\/ID&gt;\r\n  &lt;FirstName&gt;John&lt;\/FirstName&gt;\r\n  &lt;LastName&gt;Doe&lt;\/LastName&gt;\r\n  &lt;Birthday&gt;1990-12-30T00:00:00&lt;\/Birthday&gt;\r\n  &lt;RoomNo&gt;310&lt;\/RoomNo&gt;\r\n  &lt;HomeAddress&gt;\r\n    &lt;Street&gt;12 Main str.&lt;\/Street&gt;\r\n    &lt;Zip&gt;23322&lt;\/Zip&gt;\r\n    &lt;City&gt;Boston&lt;\/City&gt;\r\n    &lt;Country&gt;USA&lt;\/Country&gt;\r\n  &lt;\/HomeAddress&gt;\r\n&lt;\/Patient&gt;<\/pre>\n<h2>An Array of Objects Serialization<\/h2>\n<p>In order to serialize an array of objects, we have to instruct <code>XmlSerializer<\/code> to expect objects of type <code>Patient[]<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"13\">var arr = new Patient[]\r\n{\r\n    new Patient()\r\n    {\r\n      ...\r\n    },\r\n    new Patient()\r\n    {\r\n     \u00a0... \r\n    }\r\n};\r\n\r\nvar arrSerializer = new XmlSerializer(typeof(Patient[]));\r\nusing (var writer = new StreamWriter(\"patients.xml\"))\r\n{\r\n    arrSerializer.Serialize(writer, arr);\r\n}\r\n<\/pre>\n<p>The resulting XML now contains a Root Element with the name <code>ArrayOfPatient<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\" data-enlighter-highlight=\"2\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;ArrayOfPatient xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\"&gt;\r\n  &lt;Patient&gt;\r\n    ...\r\n  &lt;\/Patient&gt;\r\n  &lt;Patient&gt;\r\n    ...\r\n  &lt;\/Patient&gt;\r\n&lt;\/ArrayOfPatient&gt;<\/pre>\n<h2>Serializing Classes with Lists of Objects to XML<\/h2>\n<p>The <code>XmlSerializer<\/code> class can also serialize classes that contain lists (or arrays) of objects:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"9\">public class Patient\r\n{\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public DateTime Birthday { get; set; }\r\n    public int RoomNo { get; set; }\r\n    public Address HomeAddress { get; set; }\r\n    public List&lt;Measurement&gt; Measurements {get; set;}    \r\n}<\/pre>\n<p>Each <code>Measurement<\/code> stores temperature readings for the patient:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Measurement\r\n{\r\n    public DateTime TimeTaken { get; set; }\r\n    public decimal Temp { get; set; }\r\n}<\/pre>\n<p>We can serialize a <code>Patient<\/code> object in the same way as before:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patient = new Patient()\r\n{\r\n    ID = 232323,\r\n    ...\r\n    HomeAddress = new Address()\r\n    {\r\n        Street = \"12 Main str.\",\r\n        ...\r\n    },\r\n    Measurements = new List&lt;Measurement&gt;()\r\n    {\r\n        new Measurement() { TimeTaken = new DateTime(2022, 1, 1, 17, 50, 0), Temp = 38.4M },\r\n        new Measurement() { TimeTaken = new DateTime(2022, 1, 1, 22, 00, 0), Temp = 39.1M },\r\n        new Measurement() { TimeTaken = new DateTime(2022, 1, 2, 6, 30, 0), Temp = 37.3M }\r\n    }\r\n};\r\n\r\nvar serializer = new XmlSerializer(typeof(Patient));\r\nusing (var writer = new StreamWriter(\"patients.xml\"))\r\n{\r\n    serializer.Serialize(writer, patient);\r\n}\r\n<\/pre>\n<p>Our XML file will now have an array of elements with the corresponding measurements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;Patient xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\"&gt;\r\n  ....\r\n  &lt;Measurements&gt;\r\n    &lt;Measurement&gt;\r\n      &lt;TimeTaken&gt;2022-01-01T17:50:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;38.4&lt;\/Temp&gt;\r\n    &lt;\/Measurement&gt;\r\n    &lt;Measurement&gt;\r\n      &lt;TimeTaken&gt;2022-01-01T22:00:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;39.1&lt;\/Temp&gt;\r\n    &lt;\/Measurement&gt;\r\n    &lt;Measurement&gt;\r\n      &lt;TimeTaken&gt;2022-01-02T06:30:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;37.3&lt;\/Temp&gt;\r\n    &lt;\/Measurement&gt;\r\n  &lt;\/Measurements&gt;\r\n&lt;\/Patient&gt;<\/pre>\n<h2><a id=\"attributes\"><\/a>Controlling XML Serialization in C#<\/h2>\n<p>We can influence the serialization of an object with the use of C# Attributes. In this way, we can serialize an object property as an XML attribute (instead of an XML element). Moreover, we can select a different name for an element tag. We can also prevent a property from appearing in the resulting XML.<\/p>\n<p>So, let&#8217;s start with the <code>Patient<\/code> class modification by adding the required attributes:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1,4,8,10,13,14\">[XmlRoot(\"PatientInfo\")]\r\npublic class Patient\r\n{\r\n    [XmlAttribute (\"PatientID\")]\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    [XmlIgnore]\r\n    public DateTime Birthday { get; set; }\r\n    [XmlElement(\"RoomNumber\")]\r\n    public int RoomNo { get; set; }\r\n    public Address HomeAddress { get; set; }\r\n    [XmlArray(\"TemperatureReadings\")]\r\n    [XmlArrayItem(\"TemperatureReading\")]\r\n    public List&lt;Measurement&gt; Measurements {get; set;}    \r\n}<\/pre>\n<p>First of all, we can change the name of the Root Element from <code>Patient<\/code> to <code>PatientInfo<\/code>, using of <code>XmlRoot<\/code> annotation.<\/p>\n<p>Next, we choose to serialize the <code>ID<\/code> property as an <code>XmlAttribute<\/code>, under the name <code>PatientID<\/code>.<\/p>\n<p>The <code>XmlIgnore<\/code> annotation prevents a property from appearing in the XML. Here, we use it to omit the patient&#8217;s birthday from the resulting file.<\/p>\n<p>Furthermore, when our object contains a list &#8211; or an array &#8211; of objects, we can use the <code>XmlArray<\/code> and <code>XmlArrayItem<\/code> attributes to modify the way they will be serialized. The <code>XmlArray<\/code> attribute changes the array&#8217;s tag name from <code>Measurements<\/code> to <code>TemperatureReadings<\/code>. Also, <code>XmlArrayItem<\/code> provides a new name for each element of the <code>Measurements<\/code> array.<\/p>\n<p>Finally, let&#8217;s add the <code>XmlText<\/code> attribute to the <code>Address<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"6\">public class Address\r\n{\r\n    public string Street { get; set; }\r\n    public string Zip { get; set; }\r\n    public string City { get; set; }\r\n    [XmlText]\r\n    public string Country { get; set; }\r\n}<\/pre>\n<p>With the use of <code>XmlText<\/code>, we are going to serialize the <code>Country<\/code> property as plain text inside the Address element.<\/p>\n<p>As a result, we will have a different XML file:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\" data-enlighter-highlight=\"2,9,10,12-13\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;PatientInfo xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\" PatientID=\"232323\"&gt;\r\n  &lt;FirstName&gt;John&lt;\/FirstName&gt;\r\n  &lt;LastName&gt;Doe&lt;\/LastName&gt;\r\n  &lt;RoomNumber&gt;310&lt;\/RoomNumber&gt;\r\n  &lt;HomeAddress&gt;\r\n    &lt;Street&gt;12 Main str.&lt;\/Street&gt;\r\n    &lt;Zip&gt;23322&lt;\/Zip&gt;\r\n    &lt;City&gt;Boston&lt;\/City&gt;\r\n    USA\r\n  &lt;\/HomeAddress&gt;\r\n  &lt;TemperatureReadings&gt;\r\n    &lt;TemperatureReading&gt;\r\n      &lt;TimeTaken&gt;2022-01-01T17:50:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;38.4&lt;\/Temp&gt;\r\n    &lt;\/TemperatureReading&gt;\r\n    &lt;TemperatureReading&gt;\r\n      &lt;TimeTaken&gt;2022-01-01T22:00:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;39.1&lt;\/Temp&gt;\r\n    &lt;\/TemperatureReading&gt;\r\n    &lt;TemperatureReading&gt;\r\n      &lt;TimeTaken&gt;2022-01-02T06:30:00&lt;\/TimeTaken&gt;\r\n      &lt;Temp&gt;37.3&lt;\/Temp&gt;\r\n    &lt;\/TemperatureReading&gt;\r\n  &lt;\/TemperatureReadings&gt;\r\n&lt;\/PatientInfo&gt;<\/pre>\n<h2>Handling Derived Classes<\/h2>\n<p>A special case of the list (or array) serialization arises when a list contains references to objects of derived classes. This usually happens with <a href=\"https:\/\/code-maze.com\/csharp-polymorphism\/\" target=\"_blank\" rel=\"nofollow noopener\">polymorphism<\/a>. Let&#8217;s suppose we have a <code>Person<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Person\r\n{\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public DateTime Birthday { get; set; }\r\n}\r\n<\/pre>\n<p>This class serves as the base for the creation of the <code>Patient<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Patient: Person\r\n{\r\n    public int RoomNo { get; set; }\r\n}\r\n<\/pre>\n<p>And the <code>Doctor<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Doctor: Person\r\n{ \r\n    public string Specialization { get; set; }\r\n}<\/pre>\n<p>Now, let&#8217;s create a list that contains references to objects of both types:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var people = new List&lt;Person&gt;()\r\n{\r\n    new Doctor()\r\n    {\r\n        ID = 777,\r\n        FirstName = \"Jane\",\r\n        LastName = \"Doe\",\r\n        Birthday = new DateTime(1975, 3, 5),\r\n        Specialization = \"Cardiologist\"\r\n    },\r\n    new Patient()\r\n    {\r\n        ID = 888,\r\n        FirstName = \"John\",\r\n        LastName = \"Doe\",\r\n        Birthday = new DateTime(1980, 3, 21),\r\n        RoomNo = 301\r\n    }\r\n};\r\n\r\nvar serializer = new XmlSerializer(typeof(List&lt;Person&gt;));\r\nusing (TextWriter writer = new StreamWriter(\"patients.xml\"))\r\n{\r\n    serializer.Serialize(writer, people);\r\n}\r\n<\/pre>\n<p>If we try to serialize this list, we will get an <code>InvalidOperationException<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">InvalidOperationException: The type NamsepaceXXX.Doctor was not expected. \r\nUse the XmlInclude or SoapInclude attribute to specify types that are not known statically.<\/pre>\n<p>As the exception detail hints, we should specify the derived types using the <code>XmlInclude<\/code> attribute:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1,2\">[XmlInclude(typeof(Doctor))]\r\n[XmlInclude(typeof(Patient))]\r\npublic class Person\r\n{\r\n    public int ID { get; set; }\r\n    public string FirstName { get; set; }\r\n    public string LastName { get; set; }\r\n    public DateTime Birthday { get; set; }\r\n}\r\n\r\n<\/pre>\n<p>In this case, the serialization completes successfully. The resulting XML contains both objects with their respective content:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;ArrayOfPerson xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\"&gt;\r\n  &lt;Person xsi:type=\"Doctor\"&gt;\r\n    &lt;ID&gt;777&lt;\/ID&gt;\r\n    &lt;FirstName&gt;Jane&lt;\/FirstName&gt;\r\n    &lt;LastName&gt;Doe&lt;\/LastName&gt;\r\n    &lt;Birthday&gt;1975-03-05T00:00:00&lt;\/Birthday&gt;\r\n    &lt;Specialization&gt;Cardiologist&lt;\/Specialization&gt;\r\n  &lt;\/Person&gt;\r\n  &lt;Person xsi:type=\"Patient\"&gt;\r\n    &lt;ID&gt;888&lt;\/ID&gt;\r\n    &lt;FirstName&gt;John&lt;\/FirstName&gt;\r\n    &lt;LastName&gt;Doe&lt;\/LastName&gt;\r\n    &lt;Birthday&gt;1980-03-21T00:00:00&lt;\/Birthday&gt;\r\n    &lt;RoomNo&gt;301&lt;\/RoomNo&gt;\r\n  &lt;\/Person&gt;\r\n&lt;\/ArrayOfPerson&gt;<\/pre>\n<h2>Conclusion<\/h2>\n<p>In this post, we have seen how to perform XML serialization in C#. More specifically, we have learned to serialize simple and complex objects, as well as arrays and lists of objects. Finally, we have learned how to alter the structure of the resulting XML file with the use of attributes.<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we are going to learn about serializing objects to XML in C#. So, what is XML Serialization?\u00a0 It is the transformation of the public fields and property values of an object (without type information) into an XML stream. After the main definition, we can continue to see how to serialize objects to [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12,1033],"tags":[928,1020],"class_list":["post-62427","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","category-xml","tag-serialization","tag-xml","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Serializing Objects to XML in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this post, we&#039;ll learn about serializing objects to XML in C#, i.e. transforming an object&#039;s contents into an XML document\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-xml-serialization\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Serializing Objects to XML in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this post, we&#039;ll learn about serializing objects to XML in C#, i.e. transforming an object&#039;s contents into an XML document\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-xml-serialization\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-01-17T06:50:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-01-17T07:02:17+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Serializing Objects to XML in C#\",\"datePublished\":\"2022-01-17T06:50:56+00:00\",\"dateModified\":\"2022-01-17T07:02:17+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/\"},\"wordCount\":859,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"Serialization\",\"XML\"],\"articleSection\":[\"C#\",\"XML\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-xml-serialization\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/\",\"url\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/\",\"name\":\"Serializing Objects to XML in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-01-17T06:50:56+00:00\",\"dateModified\":\"2022-01-17T07:02:17+00:00\",\"description\":\"In this post, we'll learn about serializing objects to XML in C#, i.e. transforming an object's contents into an XML document\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-xml-serialization\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-xml-serialization\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Serializing Objects to XML in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Serializing Objects to XML in C# - Code Maze","description":"In this post, we'll learn about serializing objects to XML in C#, i.e. transforming an object's contents into an XML document","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-xml-serialization\/","og_locale":"en_US","og_type":"article","og_title":"Serializing Objects to XML in C# - Code Maze","og_description":"In this post, we'll learn about serializing objects to XML in C#, i.e. transforming an object's contents into an XML document","og_url":"https:\/\/code-maze.com\/csharp-xml-serialization\/","og_site_name":"Code Maze","article_published_time":"2022-01-17T06:50:56+00:00","article_modified_time":"2022-01-17T07:02:17+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Serializing Objects to XML in C#","datePublished":"2022-01-17T06:50:56+00:00","dateModified":"2022-01-17T07:02:17+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/"},"wordCount":859,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["Serialization","XML"],"articleSection":["C#","XML"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-xml-serialization\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/","url":"https:\/\/code-maze.com\/csharp-xml-serialization\/","name":"Serializing Objects to XML in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-01-17T06:50:56+00:00","dateModified":"2022-01-17T07:02:17+00:00","description":"In this post, we'll learn about serializing objects to XML in C#, i.e. transforming an object's contents into an XML document","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-xml-serialization\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-xml-serialization\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Serializing Objects to XML in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/62427","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=62427"}],"version-history":[{"count":2,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/62427\/revisions"}],"predecessor-version":[{"id":63271,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/62427\/revisions\/63271"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=62427"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=62427"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=62427"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}