I am trying to figure out how to do XML serialization.
This is how I want my XML document too look like in the end
<course>
<name></name>
<backgroundColor></backgroundColor>
<fontColor></fontColor>
<sharingKey></sharingKey>
<task id="">
<taskName></taskName>
<description></description>
</task>
<task id="">
<taskName></taskName>
<description></description>
</task>
</course>
So far mine looks like
<?xml version="1.0" encoding="utf-8"?>
<Course xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>name</name>
<backgroundColor>test</backgroundColor>
<fontColor>test2</fontColor>
<sharingKey>9324bfab-6cc7-49e5-84f7-56130b8dc099</sharingKey>
<task id="first Task" />
<task id="Second task" />
</Course>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
[XmlRoot("Course")]
public class MyWrapper
{
public MyWrapper()
{
TaskList = new List<Tasks>();
}
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("backgroundColor")]
public string BackgroundColor { get; set; }
[XmlElement("fontColor")]
public string FontColor { get; set; }
[XmlElement("sharingKey")]
public Guid SharingKey { get; set; }
[XmlElement("task")]
public List<Tasks> TaskList { get; set; }
}
public class Tasks
{
[XmlAttribute("id")]
public string Id { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Tasks task = new Tasks();
task.Id = "first Task";
Tasks task2 = new Tasks();
task2.Id = "Second task";
MyWrapper wrap = new MyWrapper();
wrap.BackgroundColor = "test";
wrap.FontColor = "test2";
wrap.Name = "name";
wrap.SharingKey = Guid.NewGuid();
wrap.TaskList.Add(task);
wrap.TaskList.Add(task2);
SerializeToXML(wrap);
}
static public void SerializeToXML(MyWrapper list)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));
TextWriter textWriter = new StreamWriter(@"C:\New folder\test.xml");
serializer.Serialize(textWriter, list);
textWriter.Close();
}
}
}
So my question is with the "id" for the task.
All I have is another class with this in it
[XmlAttribute("id")]
public string Id { get; set; }
How did it know to put this attribute in the task tag?
What happens if I wanted to have another property
[XmlElement()]
public string TaskName {get; set;}
Say I wanted to have an attribute with this element how would I make sure that the attribute would be with TaskName not with Task?