-
Notifications
You must be signed in to change notification settings - Fork 0
/
RentalItemDB.cs
86 lines (73 loc) · 2.98 KB
/
RentalItemDB.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading.Tasks;
namespace RentalItemMaintenance
{
public static class RentalItemDB
{
private const string Path = @"..\..\RentalItems.xml";
public static List<RentalItem> GetRentalItems()
{
// create the list
List<RentalItem> rentalItems = new List<RentalItem>();
// create the XmlReaderSettings object
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
// create the XmlReader object
XmlReader xmlIn = XmlReader.Create(Path, settings);
// read past all nodes to the first RentalItem node
if (xmlIn.ReadToDescendant("RentalItem"))
{
// create one RentalItem object for each RentalItem node
do
{
RentalItem rentalItem = new RentalItem();
xmlIn.ReadStartElement("RentalItem");
rentalItem.StockNo =
xmlIn.ReadElementContentAsDecimal();
rentalItem.Description =
xmlIn.ReadElementContentAsString();
rentalItem.Rating =
xmlIn.ReadElementContentAsString();
rentalItems.Add(rentalItem);
}
while (xmlIn.ReadToNextSibling("RentalItem"));
}
// close the XmlReader object
xmlIn.Close();
return rentalItems;
}
public static void SaveRentalItems(List<RentalItem> rentalItems)
{
// create the XmlWriterSettings object
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
// create the XmlWriter object
XmlWriter xmlOut = XmlWriter.Create(Path, settings);
// write the start of the document
xmlOut.WriteStartDocument();
xmlOut.WriteStartElement("RentalItem");
// write each rentalItem object to the xml file
foreach (RentalItem rentalItem in rentalItems)
{
xmlOut.WriteStartElement("RentalItem");
xmlOut.WriteElementString("StockNo",
Convert.ToString(rentalItem.StockNo));
xmlOut.WriteElementString("Description",
rentalItem.Description);
xmlOut.WriteElementString("Rating",
rentalItem.Rating);
xmlOut.WriteEndElement();
}
// write the end tag for the root element
xmlOut.WriteEndElement();
// close the xmlWriter object
xmlOut.Close();
}
}
}