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.

[Serializable()]
 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");
aBook.BookReaders.Add("Pedro");
aBook.BookReaders.Add("Manuel");

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);
theFile.Close();

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="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BookName>Notes From Underground</BookName>
  <BookWriter>Dostoyevski</BookWriter>
  <BookReaders>
    <string>Jose Angel</string>
    <string>Pedro</string>
    <string>Manuel</string>
  </BookReaders>
</Book>

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:
                        Console.WriteLine("<"+newXmlReader.Value+">");
                        break;
                    case XmlNodeType.Element:
                        Console.WriteLine("<" + newXmlReader.Name + ">");
                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine(newXmlReader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        Console.WriteLine("</" + newXmlReader.Name + ">");
                        break;
                }
            }
            Console.ReadLine();

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

Advertisements
This entry was posted in C# and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s