Skip to content

.Net XML Serializer / Deserializer

./DotNetXMLSerializer MichalSzalkowski "/home/kali/workspace/code/dot-net-example.xml"
./DotNetXMLDeserializer ~/workspace/code/dot-net-example.xml
dotnet build

DotNetXMLSerializer - Program.cs

using System;
using System.IO;
using System.Xml.Serialization;

namespace DotNetXMLSerializer
{
    class Program
    {
        static void Main(string[] args)
        {
            MyText myText = new MyText();
            myText.text = args[0];
            String xmlLocationPath = args[1];

            MySerializer(myText, xmlLocationPath);
        }

        static void MySerializer(MyText txt, String xmlLocationPath)
        {
            var ser = new XmlSerializer(typeof(MyText));
            TextWriter writer = new StreamWriter(xmlLocationPath);
            ser.Serialize(writer, txt);
            writer.Close();
        }
    }
}

namespace DotNetXMLSerializer
{
    public class MyText
    {
        private String _text = "Default";

        public String text
        {
            get { return _text; }
            set { _text = value; Console.WriteLine("Console text = " + _text); }
        }
    }
}

cat dot-net-example.xml
<?xml version="1.0" encoding="utf-8"?>
<MyText xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <text>MichalSzalkowski</text>
</MyText>

DotNetXMLDeserializer - Program.cs

using System.IO;
using System.Xml.Serialization;
using DotNetXMLSerializer;

namespace DotNetXMLDeserializer
{
    class Program
    {
        static void Main(string[] args)
        {
            var fileStream = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            var streamReader = new StreamReader(fileStream);
            XmlSerializer serializer = new XmlSerializer(typeof(MyText));
            serializer.Deserialize(streamReader);
        }
    }
}