请帮我写一段C#代码实现课程表的添加删除修改和读取课程表以XML的形式储存在ClassToolboxDataSchoolTimetablexml文件中
以下是一个示例的C#代码,实现了课程表的添加、删除、修改和读取,课程表以XML的形式存储在".\ClassToolboxData\SchoolTimetable.xml"文件中。
using System;
using System.Xml;
namespace SchoolTimetable
{
class Program
{
static void Main(string[] args)
{
string filePath = @".\ClassToolboxData\SchoolTimetable.xml"; // 课程表文件路径
// 添加示例课程
AddCourse(filePath, "星期一", "09:00", "数学");
AddCourse(filePath, "星期二", "10:00", "英语");
// 读取并打印课程表
ReadTimetable(filePath);
// 修改课程
UpdateCourse(filePath, "星期一", "09:00", "化学");
// 读取并打印课程表
ReadTimetable(filePath);
// 删除课程
DeleteCourse(filePath, "星期二", "10:00");
// 读取并打印课程表
ReadTimetable(filePath);
}
// 添加课程
static void AddCourse(string filePath, string day, string time, string name)
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode root = doc.SelectSingleNode("Timetable");
XmlNode courseNode = doc.CreateElement("Course");
XmlAttribute dayAttr = doc.CreateAttribute("Day");
dayAttr.Value = day;
courseNode.Attributes.Append(dayAttr);
XmlAttribute timeAttr = doc.CreateAttribute("Time");
timeAttr.Value = time;
courseNode.Attributes.Append(timeAttr);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.InnerText = name;
courseNode.AppendChild(nameNode);
root.AppendChild(courseNode);
doc.Save(filePath);
}
// 删除课程
static void DeleteCourse(string filePath, string day, string time)
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList courseNodes = doc.SelectNodes("//Course[@Day='" + day + "' and @Time='" + time + "']");
foreach (XmlNode courseNode in courseNodes)
{
courseNode.ParentNode.RemoveChild(courseNode);
}
doc.Save(filePath);
}
// 修改课程
static void UpdateCourse(string filePath, string day, string time, string newName)
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList courseNodes = doc.SelectNodes("//Course[@Day='" + day + "' and @Time='" + time + "']");
foreach (XmlNode courseNode in courseNodes)
{
XmlNode nameNode = courseNode.SelectSingleNode("Name");
nameNode.InnerText = newName;
}
doc.Save(filePath);
}
// 读取并打印课程表
static void ReadTimetable(string filePath)
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList courseNodes = doc.SelectNodes("//Course");
Console.WriteLine("课程表:");
foreach (XmlNode courseNode in courseNodes)
{
string day = courseNode.Attributes["Day"].Value;
string time = courseNode.Attributes["Time"].Value;
string name = courseNode.SelectSingleNode("Name").InnerText;
Console.WriteLine(day + " " + time + " " + name);
}
Console.WriteLine();
}
}
}
上述代码通过使用XmlDocument类来加载、修改和保存XML文件。其中,AddCourse方法用于添加课程,DeleteCourse方法用于删除课程,UpdateCourse方法用于修改课程,ReadTimetable方法用于读取并打印课程表。
需要注意的是,使用该代码前需确保.\\ClassToolboxData\\SchoolTimetable.xml文件已存在,并且符合以下的XML格式:
<Timetable>
<Course Day="星期一" Time="09:00">
<Name>数学</Name>
</Course>
<Course Day="星期二" Time="10:00">
<Name>英语</Name>
</Course>
</Timetable>
你可以根据实际需求对代码进行修改和扩展
原文地址: https://www.cveoy.top/t/topic/ikN4 著作权归作者所有。请勿转载和采集!