Reputation: 155
I want to create a XML file to store data using a dataset in c#. The classes are as follows
public class Person
{
[Key]
public string id { get; set; }
public string name { get; set; }
public virtual ICollection<Dependant> dependants { get; set; }
}
public class Dependant
{
public string name { get; set; }
public string email { get; set; }
}
The final XML file that is produced should be
<db>
<Person>
<id>1</id>
<name>John</name>
<dependants>
<dependant>
<name>test1</name>
<email>test1</email>
</dependant>
<dependant>
<name>test2</name>
<email>test2</email>
</dependant>
</dependants>
<Person>
<db>
The requirement is to use it like an database and the data should be added using
Dataset db = new Dataset();
List<Dependant> dpList = new List<Dependant>();
Dataset.PersonRow pr = new Dataset.PersonRow();
pr.name = "name";
pr.id = "pr1";
Dependant dp = new Dependant();
dp.name = "dp1";
dp.email = "dp1";
dpList.Add(dp);
dp.dependants = dpList;
db.Person.AddNewPersonRow(dp);
db.AcceptChanges();
db.WriteXML("localData");
This is the structure that should be followed according to the lecturer.
I'm having the problem in creating the datatable as I do not know the datatypr that should be used for the list, when creating the datatable.
How can i acheive this?
Im new to c# so any help would be great!
Upvotes: 1
Views: 359
Reputation: 34433
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataBase db = new DataBase()
{
Person = new Person()
{
dependants = new List<Dependant>()
}
};
XDocument doc = XDocument.Parse("<db><Person></Person></db>");
XElement xPerson = doc.Descendants("Person").FirstOrDefault();
Person person = db.Person;
xPerson.Add(new object[] {
new XElement("id", person.id),
new XElement("name", person.name),
new XElement("dependants")
});
XElement xDependants = xPerson.Element("dependants");
foreach (Dependant dependant in person.dependants)
{
xDependants.Add(new XElement("dependant"), new object[] {
new XElement("name", dependant.name),
new XElement("email", dependant.email)
});
}
}
}
public class Person
{
public string id { get; set; }
public string name { get; set; }
public virtual ICollection<Dependant> dependants { get; set; }
}
public class Dependant
{
public string name { get; set; }
public string email { get; set; }
}
public class DataBase
{
public Person Person { get; set; }
}
}
Upvotes: 1