SoFunction
Updated on 2025-03-02

Example of simple usage of C# xmlSerializer

This article describes the simple usage of C# xmlSerializer. Share it for your reference, as follows:

Go to the entity class first

public class Entity
{
    public Entity()
    {
    }
    public Entity(string c, string f)
    {
      name = c;
      school = f;
    }
    public string name;
    public string school;
}

Declaration on use

List<Entity> entityList=null;
XmlSerializer xs = new XmlSerializer(typeof(List<Entity>));

Read in

using (StreamReader sr = new StreamReader(configPath))
{
   entityList = (sr) as List<Entity>;
}

Output

using (StreamWriter sw = (configPath))
{
  (sw, entityList);
}

Corresponding xml

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfEntity xmlns:xsd="http:///2001/XMLSchema" xmlns:xsi="http:///2001/XMLSchema-instance">
 <Entity>
  <Name>Alice</Name>
  <School>SJTU</School>
 </Entity>
 <Entity>
  <Name>Cici</Name>
  <School>CSU</School>
 </Entity>
 <Entity>
  <Name>Zero</Name>
  <School>HIT</School>
 </Entity>
</ArrayOfEntity>

PS: Here are a few more practical XML-related online tools for everyone to use:

OnlineXMLFormat/Compression Tool:
http://tools./code/xmlformat

OnlineXML/JSON mutual conversion tool:
http://tools./code/xmljson

XMLOnline compression/formatting tools:
http://tools./code/xml_format_compress

XMLCode online formatting and beautification tool:
http://tools./code/xmlcodeformat

For more information about C#, please visit the special topic of this site:Summary of XML file operation skills in C#》、《Tutorial on the usage of common C# controls》、《Summary of thread usage techniques for C# programming》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.