Coursework · Stop 5 of 10

XML handler

A C# console program: it turns a CSV list of books into an XML file and reads it back.

XML handler

Goal

Make the step from Python to C# and work with files, classes and a fixed data format.

Implementation

  • A writer class reads the CSV file (author, first name, title, separated by vertical bars) and writes it out element by element as XML.
  • A reader class loads the XML file with LINQ to XML and prints every book to the console.
  • Errors while writing are caught and reported instead of crashing the program.

Code

From CSV to XML

XMLWriter.cs
public bool WriteXML()
{
    try
    {
        string[] csvLines = File.ReadAllLines(InputCSVFile);
        XmlWriter xmlDocument = XmlWriter.Create(OutputFile);
        xmlDocument.WriteStartDocument();
        xmlDocument.WriteStartElement("Werke");
        for (int index = 1; index < csvLines.Length - 1; index++)
        {
            string[] fields = csvLines[index].Split('|');
            if (fields.Length == 3)
            {
                xmlDocument.WriteStartElement("Buch");

                xmlDocument.WriteStartElement("Name");
                xmlDocument.WriteString(fields[0]);
                xmlDocument.WriteEndElement();

                xmlDocument.WriteStartElement("Vorname");
                xmlDocument.WriteString(fields[1]);
                xmlDocument.WriteEndElement();

                xmlDocument.WriteStartElement("Titel");
                xmlDocument.WriteString(fields[2]);
                xmlDocument.WriteEndElement();

                xmlDocument.WriteEndElement();
            }
        }
        xmlDocument.WriteEndDocument();
        xmlDocument.Close();

        return true;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return false;
    }
}

Every line of the CSV file becomes a book element with name, first name and title.

What I learned

How C# handles files and text. With the right library, a format like XML takes hardly any manual work.

An unexpected error has occurred. Reload 🗙

Reconnecting to the server …

Connection failed. Trying again in seconds.

Connection failed. Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session. Please retry or reload the page.