XML Serialization and Deserialization in C# - Udemy Blog
XML Serialization and Deserialization in C# - Udemy Blog
XML Serialization and Deserialization in C# - Udemy Blog
Article Categories
Development
Serializing XML in C#
Many .NET framework objects and classes can be serialized without adding any special directives or
attributes to the code. By default, all public properties of a class are already serializable.
The example below defines a simple class in a Visual C# Console Application, and then serializes the
contents to the console window.
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 1/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
/*
*
* Udemy.com
* XML Serialization and Deserialization in C#
*
*/
using System;
using System.Xml.Serialization;
namespace XMLTest1
{
public class Test
{
public String value1;
public String value2;
}
class Program
{
static void Main(string[] args)
{
Test myTest = new Test() { value1 = "Value 1", value2 = "Value 2" };
XmlSerializer x = new XmlSerializer(myTest.GetType());
x.Serialize(Console.Out, myTest);
Console.ReadKey();
}
}
}
The actual serialization is done by an instance of the class XmlSerializer, from the
System.Xml.Serialization namespace. The serializer’s constructor requires a reference to the type of
object it should work with – which can be obtained by using the GetType() method of an instanced object,
or a call to the function typeof() and specifying the class name as the only argument.
The Serialize() method takes an object of the defined type, translates that object into XML, and then
writes the information to a defined stream (in this case, the TextWriter object of the console’s output
stream). The XML output of the sample code is shown below:
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 2/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
The names of elements and attributes in the XML output are set by the names of the properties and fields
from the object.
You can direct the output of the serialization to a wide variety of .NET streams, including MemoryStream
(with XmlWriter and StringWriter), FileStream, and NetworkStream classes. It is also possible to serialize
an object into an XmlDocument with the help of an instance of XPathNavigator, as shown in the following
example:
/*
*
* Udemy.com
* XML Serialization and Deserialization in C#
*
*/
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
namespace XMLTest1
{
public class Test
{
public String value1;
public String value2;
}
class Program
{
static void Main(string[] args)
{
XmlDocument myXml = new XmlDocument();
XPathNavigator xNav = myXml.CreateNavigator();
Test myTest = new Test() { value1 = "Value 1", value2 = "Value 2" };
XmlSerializer x = new XmlSerializer(myTest.GetType());
using (var xs = xNav.AppendChild())
{
x.Serialize(xs, myTest);
}
Console.WriteLine(myXml.OuterXml);
Console.ReadKey();
}
}
}
In the example below, the XML output of the preceding examples is hard-coded into a string, but it could
be fetched from a network stream or external file. The XmlSerializer class is used to deserialize the string
to an instance of the Test class, and the example then prints the fields to the console. To obtain a suitable
stream that can be passed into the XmlSerializer’s constructor, a StringReader (from the System.IO
namespace) is declared.
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 3/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
/*
*
* Udemy.com
* XML Serialization and Deserialization in C#
*
*/
using System;
using System.IO;
using System.Xml.Serialization;
namespace XMLTest1
{
public class Test
{
public String value1;
public String value2;
}
class Program
{
static void Main(string[] args)
{
String xData = "<?xml version=\"1.0\" encoding=\"ibm850\"?><Test
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><value1>Value 1</value1><value2>Value
2</value2></Test>";
XmlSerializer x = new XmlSerializer(typeof(Test));
Test myTest = (Test)x.Deserialize(new StringReader(xData));
Console.WriteLine("V1: " + myTest.value1);
Console.WriteLine("V2: " + myTest.value2);
Console.ReadKey();
}
}
}
Simple arrays and generic lists generally work unmodified, and may appear identical in the final output.
For example, whether objects are declared as an array of Test objects or as a generic list of Test objects,
the XmlSerializer will write both using the same XML code:
Game Design ASP.NET ASP.NET MVC Microsoft Visual Studio Entity Framework
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 4/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
As a result, XML data in this format can be deserialized to either a generic list of Test objects, or an array
of Test objects. It is up to the programmer to specify which type of object should be used for
deserialization.
Multiple properties can be specified for an attribute by separating them with commas within the
parenthesis. This usually takes the form [attributename(property1=value1, property2=value2…)]
[XmlRoot("XTest")]
public class Test
{
[XmlElement(ElementName="V1")]
public String value1;
[XmlElement(“V2")]
public String value2;
}
Note that when you are only specifying the element name, the property name can be omitted.
Adding the XmlElement attribute, as shown above, not only sets the name to be used, but it also tells the
XmlSerializer to use an XML element for that field. You can change value1 to be an attribute of the XTest
element by declaring the field with XmlAttribute instead.
Two different attributes are used for arrays and collections. XmlArray controls the root node of the list,
and XmlArrayItem controls each element in that array.
Request a demo
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 5/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
[XmlRoot("XTest")]
public class Test
{
[XmlElement(ElementName="V1")]
public String value1;
[XmlElement(ElementName="V2")]
public String value2;
[XmlArray("OtherValues")]
[XmlArrayItem("OValue")]
public List others = new List();
}
In certain situations, you may want to exclude a public property or field from the output. This can be done
by adding the attribute XmlIgnore to the property in the class’s declarations:
[XmlIgnore]
public String value2;
…
Finally, when working to a defined schema, it is often necessary to remove the standard namespace
definitions that are added by the XmlSerializer. This is usually best handled when calling the Serialize()
method of the XmlSerializer instance. An optional parameter for this method specifies the namespaces to
be used, an XmlSerializerNamespaces collection, and can contain blank values.
Of course, namespaces can also be added using the same XmlSerializerNamespaces collection. However,
it is often clearer to use the Namespace property of the XmlRoot attribute in combination with the code
above.
By keeping in mind, or pre-planning, the serialization needs of the structures used in your application as
you write the classes, it is possible to add object persistence and loading of external data files to the
application with a very minimal amount of programming effort.
You do this by implementing IXmlSerializable in your classes, and including three methods that are
required for the XML serialization to work: GetSchema(), WriteXml(), and ReadXml().
A thorough explanation of working with the XmlWriter and XmlReader classes used by these methods is
beyond the scope of this article. Working with the data at such a level may draw on many different
aspects of C# programming and a variety of technologies from the .NET framework. For more advanced
C# information, C# 2012 Fundamentals at Udemy.com forms a complete course from beginner-level
projects to advanced concepts, and contains more examples of serialization in Part III.
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 6/7
11/23/24, 10:06 AM XML Serialization and Deserialization in C# - Udemy Blog
Recommended Articles
Learn C# Online: What You Need to C# vs. Java: What Are the Main C# Interview Questions: Can you While C
Know to Code in the Language Differences? answer them all? Progra
Teach on Udemy
Follow us
Terms
Sitemap
Featured Courses
Contact us
Cookie settings
https://blog.udemy.com/csharp-serialize-to-xml/?utm_source=adwords&utm_medium=udemyads&utm_campaign=Search_DSA_GammaCatchall_NonP_la.EN_cc.ROW-English&campaigntype=Search&portf… 7/7