Simple XML Reading,Writing and Serialization

Altough JSON became more common, XML is still an important markup language. As a snippet, I created an example project which will be creating a Books.xml file and reading it from the file.

First of all, let’s create a class called Book with parameters of book name, writer and list of readers.

 public class Book 
 private string bookName;
 public string BookName 
 get { return bookName; }
 set { bookName = value; }

 private string bookWriter;
 public string BookWriter
 get { return bookWriter; }
 set { bookWriter = value; }

 private List<string> bookReaders = new List<string>();
 public List<string> BookReaders 
 get { return bookReaders; }
 set { bookReaders = value; }

Now we create a book class and fill it with the information:

Book aBook = new Book();
aBook.BookName = "Notes From Underground";
aBook.BookWriter = "Dostoyevski";

aBook.BookReaders.Add("Jose Angel");

Next we create an XmlSerializer with the type of Book class to transform our class into an XML object. Beside, we also create a TextWriter object with StreamWriter instance to create our file. We need to import System.Xml.Serialization here. At the end, we can close the file.

XmlSerializer serializer = new XmlSerializer(typeof(Book));
TextWriter theFile = new StreamWriter(@"C:\Books.xml");
serializer.Serialize(theFile, aBook);

Note that you need to open Visual Studio with admin permission. (Click right to Visual Studio icon and select “Run as Administrator”

Once we complete the step above, we will see our file created in C: drive.

<?xml version="1.0" encoding="utf-8"?>
<Book xmlns:xsi="" xmlns:xsd="">
  <BookName>Notes From Underground</BookName>
    <string>Jose Angel</string>

In order to read the file and print it on the console screen (I am using a console application), we can create XmlTextReader object with location of file specified and print them on the console.

XmlTextReader newXmlReader = new XmlTextReader(@"C:\Books.xml");
            while (newXmlReader.Read())
                switch (newXmlReader.NodeType)
                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.Element:
                        Console.WriteLine("<" + newXmlReader.Name + ">");
                    case XmlNodeType.Text:
                    case XmlNodeType.EndElement:
                        Console.WriteLine("</" + newXmlReader.Name + ">");

Here NodeType is importan as there may be various types of elements in an XML file. See here for more information on XML NodeTypes

#class-to-xml-c, #xml, #xml-serialization