There is - at least - few ways to read/write xml data, for example:
1.
Linq to XML[
^]
2.
Xml Serialization/deserialization[
^]
Based on
this[
^] i'd suggest to create custom class collection as follow:
Car class is used to store data about single car.
public class Car
{
private string sCarName = string.Empty;
private string sCarNumber = string.Empty;
private string sCarDescription = string.Empty;
private int iCarId = 0;
public Car(string _CarName, string _CarNumber, string _CarDescription, int _CarId)
{
sCarName = _CarName;
sCarNumber = _CarNumber;
sCarDescription = _CarDescription;
iCarId = _CarId;
}
public string CarName
{
get{return sCarName;}
set{sCarName = value;}
}
public string CarNumber
{
get{return sCarNumber;}
set{sCarNumber = value;}
}
public string CarDescription
{
get{return sCarDescription;}
set{sCarDescription = value;}
}
public int CarID
{
get{return iCarId;}
set{iCarId = value;}
}
}
Cars class inherits from
CollectionBase
and is used to store list of cars (of type:
Car
):
public class Cars : CollectionBase
{
public Car Item(int index)
{
if(index<0 || index>List.Count-1)
throw new IndexOutOfRangeException();
return (Car)List[index];
}
public Car Add(Car _car)
{
_car.CarID = List.Count + 1;
int index = List.Add(_car);
return (Car)List[index];
}
void Remove(int index)
{
if(index<0 || index>List.Count-1)
throw new IndexOutOfRangeException();
List.Remove(index);
}
}
Usage:
XDocument xdoc = XDocument.Load(@"D:\CarPark.xml");
Cars CarPark = new Cars();
var cars = xdoc.Descendants("Car")
.Select(c=> new Car
(
(string)c.Element("CarName"),
(string)c.Element("CarNumber"),
(string)c.Element("CarDescription"),
(int)c.Element("CarID")
));
foreach(Car c in cars)
{
CarPark.Add(c);
}
Car cr = CarPark.Item(0);
cr.CarName = "Seat Toledo";
Note: you have to make some minor changes in xml file before you'll be able to use it:
="1.0"="utf-8"="yes"
<Cars>
<Car>
<CarName>BMW</CarName>
<CarNumber>AA2935IO</CarNumber>
<CarDescription>Nice car</CarDescription>
<CarID>1</CarID>
</Car>
<Car>
<CarName>Mersedes</CarName>
<CarNumber>AA2235IO</CarNumber>
<CarDescription>Nice car</CarDescription>
<CarID>2</CarID>
</Car>
</Cars>
If you want to implement
Save
method, which will dump all
CarPark
data into xml file, you have to loop through the collection of Cars:
XDocument xdoc = new XDocument();
XElement root = new XElement("Cars");
foreach(Car c in CarPark)
{
root.Add(new XElement("Car",
new XElement("CarName", c.CarName),
new XElement("CarNumber", c.CarNumber),
new XElement("CarDescription", c.CarDescription),
new XElement("CarID", c.CarID)));
}
xdoc.Add(root);
xdoc.Save(@"FullPathToXmlFile.xml");