|
|
XML files
Chap4_Ex29.cs
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
public class Task {
private DateTime start, end;
private string descr;
public Task(DateTime s, DateTime e, string d) {
this.start = s;
this.end = e;
this.descr = d;
}
public DateTime StartTime {
get { return start; }
set { start = value; }
}
public DateTime EndTime {
get { return end; }
set { end = value; }
}
public string Description {
get { return descr; }
set { descr = value; }
}
}
public class Organizer {
private ArrayList tl;
public Organizer() {
tl = new ArrayList();
}
public void AddTask(Task t) {
tl.Add(t);
}
public void Store(string file) {
XmlDocument doc = new XmlDocument();
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(decl);
//----- create the root element �organizer�
XmlElement rootElem = doc.CreateElement("organizer");
doc.AppendChild(rootElem);
foreach(Task t in tl) {
XmlElement tNode = doc.CreateElement("task");
XmlElement sNode = doc.CreateElement("start");
sNode.AppendChild(doc.CreateTextNode(t.StartTime.ToString()));
XmlElement eNode = doc.CreateElement("end");
eNode.AppendChild(doc.CreateTextNode(t.EndTime.ToString()));
XmlElement dNode = doc.CreateElement("description");
dNode.AppendChild(doc.CreateTextNode(t.Description));
tNode.AppendChild(sNode);
tNode.AppendChild(eNode);
tNode.AppendChild(dNode);
rootElem.AppendChild(tNode);
}
FileStream fs = new FileStream(file,FileMode.OpenOrCreate);
doc.Save(fs);
fs.Close();
}
public bool Load(string file) {
tl.Clear();
XmlDocument doc = new XmlDocument();
FileStream fs = new FileStream(file,FileMode.Open);
doc.Load(fs);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iterator = nav.Select("/organizer/*/*");
// iterate through all elements of every task element
try {
while (iterator.MoveNext()) {
//Console.WriteLine(iterator.Current.Value);
DateTime s = DateTime.Parse(iterator.Current.Value);
iterator.MoveNext();
DateTime e = DateTime.Parse(iterator.Current.Value);
iterator.MoveNext();
tl.Add(new Task(s, e, iterator.Current.Value));
}
} catch(Exception e) {
Console.WriteLine(e.Message);
fs.Close();
return false;
}
fs.Close();
return true;
}
}
public class Cap4_Ex29_Test {
public static void Main(string[] args) {
Organizer o = new Organizer();
o.AddTask(new Task(new DateTime(2004,12,1,1,1,1,1), new DateTime(2004,12,1,1,2,1,1),"Shopping with friends"));
o.AddTask(new Task(new DateTime(2004,12,1,1,2,1,1), new DateTime(2004,12,1,1,3,1,1),"Working for the DotNet-book"));
o.AddTask(new Task(new DateTime(2004,12,1,1,3,1,1), new DateTime(2004,12,1,1,4,1,1),"Teaching Programming for Students"));
o.Store("organizer.xml");
o.Load("organizer.xml");
}
}
|
|