一.添加数据:
public bool AddArticle(string NewsTitle, string NewsContent, string NewsClassID)
{
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath(articlePath)); //装载文章xml
int newID = 1;
if (doc.DocumentElement.SelectSingleNode("//Article[@ID]") != null)
{ //最后一个文章ID+1就是新的文章ID
newID = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("//Article[last()]").Attributes["ID"].Value) + 1;
}
XmlElement el = doc.CreateElement("Article");
XmlAttribute id = doc.CreateAttribute("ID");
id.Value = newID.ToString();
XmlAttribute title = doc.CreateAttribute("Title");
title.Value = NewsTitle;
XmlAttribute date = doc.CreateAttribute("Date");
date.Value = DateTime.Now.ToString();
XmlAttribute classID = doc.CreateAttribute("ClassID");
classID.Value = NewsClassID;
XmlCDataSection content = doc.CreateCDataSection(NewsContent);
el.Attributes.Append(id);
el.Attributes.Append(title);
el.Attributes.Append(classID);
el.Attributes.Append(date);
el.AppendChild(content);
doc.DocumentElement.AppendChild(el);
doc.Save(HttpContext.Current.Server.MapPath(articlePath));
return true;
}
二.修改数据
public bool EditArticle(string NewsTitle, string NewsContent, string NewsID)
{
try
{
XmlDocument document = new XmlDocument();
document.Load(HttpContext.Current.Server.MapPath(this.articlePath));
XmlNode node = document.DocumentElement.SelectSingleNode("Article[@ID=" + NewsID + "]");
if (node != null)
{
node.Attributes["Title"].Value = NewsTitle;
node.FirstChild.Value = NewsContent;
}
document.Save(HttpContext.Current.Server.MapPath(this.articlePath));
return true;
}
catch
{
return false;
}
}
三.删除数据
public bool DeleteArticle(string NewsID)
{
bool flag = false;
try
{
XmlDocument document = new XmlDocument();
document.Load(HttpContext.Current.Server.MapPath(this.articlePath));
XmlNode oldChild = document.DocumentElement.SelectSingleNode("Article[@ID=" + NewsID + "]");
if (oldChild != null)
{
oldChild.ParentNode.RemoveChild(oldChild);
}
document.Save(HttpContext.Current.Server.MapPath(this.articlePath));
}
catch
{
flag = false;
}
return flag;
}
浙公网安备 33010602011771号