Aleks D Aleks D - 8 days ago 4x
C# Question

XML still empty?

This may be a very stupid question, but I can't seem to get this thing working.
I'm trying to form an XML with the following structure, and be able to add additional data into it at any point in time, as well as read the data.
Right now all I get is:

<?xml version="1.0" encoding="utf-8"?>
<sessions />

What I want

<?xml version="1.0" encoding="utf-8"?>
<session date="14.10.2016" time="17:15" amount="3">
<sessions />

My C# code

static void Main(string[] args)
Console.WriteLine("Test XML");



static List<String> folderList = new List<String>();

private static string generateRandom(int min, int max)
Random rnd = new Random();
return rnd.Next(min, max).ToString();

public static string pathToXml = "test_aleksei2.xml";
public static void createXML()

XmlTextWriter textWritter = new XmlTextWriter(pathToXml, Encoding.UTF8); //Creating file
textWritter.WriteStartDocument(); //XML header
textWritter.WriteStartElement("sessions"); //XML head
textWritter.WriteEndElement(); //end writing element
textWritter.Close(); //close XmlTextWriter


public static void XML()

Console.WriteLine("XML function being executed");
XmlDocument document = new XmlDocument(); //using XmlDocument to Read
document.Load(pathToXml); //loading XML
XmlNode element = document.CreateElement("session"); //parent element

XmlAttribute date = document.CreateAttribute("date"); //creating attribute
date.Value = "14.10.2016";
element.Attributes.Append(date); //append attribute to element

XmlAttribute time = document.CreateAttribute("time");
time.Value = generateRandom(0, 23) + ":" + generateRandom(1, 59);

XmlAttribute amount = document.CreateAttribute("amount");
amount.Value = generateRandom(1, 10);

XmlNode folder = null;

for (int i = 0; i < folderList.Count; i++)
Console.WriteLine(folderList[i]+" - " + i + "/" + folderList.Count);
folder = document.CreateElement("Folder");
folder.InnerText = folderList[i];



Help please, I don't understand what I'm doing wrong. If I just c&p I might not even learn what's the issue here... Thank you in advance


In your XML method, you never append the session element to the document after you create it. So, even though you create and add all those children to the element, none of it gets added to the document.

You need to add this line before you save the document: